"""POST /preferences/email/test for [mugi_backend._build_app](mugi_backend.py)."""
from __future__ import annotations

import logging
from typing import Any

from fastapi import Request as FRequest
from fastapi.responses import JSONResponse

from utils.mugi_email_preferences import (
    prepare_email_config_for_response,
    select_email_account_for_test,
)
from utils.sliding_window_rate_limiter import SlidingWindowRateLimiter

_log = logging.getLogger(__name__)


def register_email_preferences_routes(fastapi_app: Any) -> None:
    email_test_limiter = SlidingWindowRateLimiter(max_calls=12, window_seconds=60.0)

    @fastapi_app.post("/preferences/email/test")
    async def test_email_connection(request: FRequest):
        if not email_test_limiter.allow():
            return JSONResponse(content={"ok": False, "error": "Rate limit exceeded. Please wait a moment."}, status_code=429)
        try:
            body = await request.json()
        except Exception:
            body = {}
        if not isinstance(body, dict):
            body = {}
        from core import get_config
        config = get_config()
        email_cfg, changed = prepare_email_config_for_response(config)
        if changed:
            config["email"] = email_cfg
            try:
                from core import save_config
                save_config(config)
            except Exception:
                _log.debug("Failed to save normalized email config during test route", exc_info=True)
        account_id = str(body.get("account_id") or "").strip()
        selected = select_email_account_for_test(email_cfg, account_id, body)
        has_explicit_creds = bool(
            str(body.get("imap_host") or "").strip() and str(body.get("imap_user") or "").strip()
        )
        if account_id and str(selected.get("id") or "") != account_id and not has_explicit_creds:
            return JSONResponse(content={"ok": False, "error": f'Unknown account_id "{account_id}".'}, status_code=400)
        host = selected["imap_host"]
        port_val = selected["imap_port"]
        try:
            port = int(port_val) if port_val is not None else 993
        except Exception:
            return JSONResponse(content={"ok": False, "error": "Invalid IMAP port."}, status_code=400)
        user = selected["imap_user"]
        password = (body.get("password") or "").strip()
        selected_id = selected["id"]
        if not password:
            try:
                from persistence import keychain_get_imap_password, keychain_get_imap_password_for_account
                if selected_id:
                    password = (keychain_get_imap_password_for_account(selected_id) or "").strip()
                if not password:
                    password = (keychain_get_imap_password() or "").strip()
            except Exception:
                _log.debug("Failed to get IMAP password from keychain", exc_info=True)
        if not host or not user:
            return JSONResponse(content={"ok": False, "error": "IMAP server and email/user are required."}, status_code=400)
        if not password:
            return JSONResponse(content={"ok": False, "error": "Password is required. Enter it in the Access pane and Save first."}, status_code=400)
        try:
            from tools.email_tools import test_imap_connection
            ok, err = test_imap_connection(host, port, user, password)
            if ok:
                return JSONResponse(content={"ok": True})
            return JSONResponse(content={"ok": False, "error": err or "Connection failed."})
        except Exception as e:
            return JSONResponse(content={"ok": False, "error": str(e)})
