"""Mark an email as read via Gmail IMAP4_SSL."""

import asyncio
import imaplib

from fliiq.runtime.google_auth import resolve_gmail_creds

IMAP_HOST = "imap.gmail.com"
IMAP_PORT = 993


def _mark_seen(address: str, auth_method: str, credential: str, message_id: str) -> dict:
    """Blocking IMAP store — runs in threadpool."""
    try:
        conn = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT, timeout=30)
    except Exception as e:
        raise ValueError(f"IMAP connection failed: {e}")

    try:
        if auth_method == "oauth2":
            auth_string = f"user={address}\x01auth=Bearer {credential}\x01\x01"
            conn.authenticate("XOAUTH2", lambda _: auth_string.encode())
        else:
            conn.login(address, credential)
    except imaplib.IMAP4.error as e:
        conn.logout()
        if auth_method == "oauth2":
            raise ValueError(
                f"Gmail IMAP OAuth failed for {address}: {e}. "
                "Try 'fliiq google auth' to re-authorize."
            )
        raise ValueError(
            "Gmail IMAP authentication failed. Check GMAIL_ADDRESS and GMAIL_APP_PASSWORD."
        )

    try:
        conn.select("INBOX")
        status, _data = conn.uid("store", message_id, "+FLAGS", "\\Seen")
        if status != "OK":
            raise ValueError(f"Failed to mark email {message_id} as read: {status}")
        return {"status": f"Email {message_id} marked as read."}
    except imaplib.IMAP4.error as e:
        raise ValueError(f"IMAP error marking email as read: {e}")
    finally:
        try:
            conn.logout()
        except Exception:
            pass


async def handler(params: dict) -> dict:
    """Mark an email as read by IMAP UID."""
    address, auth_method, credential = await resolve_gmail_creds()

    message_id = params["message_id"]

    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        None, _mark_seen, address, auth_method, credential, message_id
    )
