"""Multi-account Gmail API OAuth + send helpers.

One Google Cloud OAuth client authorizes many Gmail accounts. Each account's
refresh token is stored in ``gmail_accounts`` and keyed by email. Sends route
by ``lead.our_email`` (or the default connected account).
"""

from __future__ import annotations

import base64
import json
import secrets
from email.message import EmailMessage
from pathlib import Path

import socket

import httplib2
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_httplib2 import AuthorizedHttp
from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from sqlalchemy.orm import Session

from app.config import settings
from app.models import GmailAccount

# Slow / flaky networks (esp. IPv6) were timing out with httplib2 defaults.
_GMAIL_HTTP_TIMEOUT_SECONDS = 60

# Prefer IPv4 — on this network IPv6 to Google often hangs ~80s+ then fails.
_orig_getaddrinfo = socket.getaddrinfo


def _getaddrinfo_prefer_ipv4(host, port, family=0, type=0, proto=0, flags=0):  # noqa: A002
    if family == 0:
        ipv4 = _orig_getaddrinfo(host, port, socket.AF_INET, type, proto, flags)
        if ipv4:
            return ipv4
    return _orig_getaddrinfo(host, port, family, type, proto, flags)


socket.getaddrinfo = _getaddrinfo_prefer_ipv4  # type: ignore[assignment]


def _gmail_http(creds: Credentials) -> AuthorizedHttp:
    return AuthorizedHttp(creds, http=httplib2.Http(timeout=_GMAIL_HTTP_TIMEOUT_SECONDS))

GMAIL_SCOPES = [
    "https://www.googleapis.com/auth/gmail.send",
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/userinfo.email",
    "openid",
]

GMAIL_READONLY_SCOPE = "https://www.googleapis.com/auth/gmail.readonly"

# In-memory OAuth CSRF states (fine for single-process / --reload lab use)
_pending_states: set[str] = set()


class GmailAuthError(Exception):
    """OAuth / credential configuration error."""


class GmailSendError(Exception):
    """Gmail API send failure."""


def _load_client_config() -> dict:
    if not settings.gmail_oauth_configured:
        raise GmailAuthError(
            "Gmail OAuth is not configured. Set GOOGLE_CLIENT_ID + GOOGLE_CLIENT_SECRET "
            "(or GOOGLE_CLIENT_SECRETS_FILE) in .env"
        )

    secrets_path = (settings.google_client_secrets_file or "").strip()
    if secrets_path:
        path = Path(secrets_path)
        if not path.is_file():
            raise GmailAuthError(f"GOOGLE_CLIENT_SECRETS_FILE not found: {path}")
        data = json.loads(path.read_text(encoding="utf-8"))
        if "web" not in data and "installed" not in data:
            raise GmailAuthError("client secrets JSON must contain 'web' or 'installed'")
        return data

    return {
        "web": {
            "client_id": settings.google_client_id,
            "client_secret": settings.google_client_secret,
            "auth_uri": "https://accounts.google.com/o/oauth2/auth",
            "token_uri": "https://oauth2.googleapis.com/token",
            "redirect_uris": [settings.google_redirect_uri],
        }
    }


def _make_flow(*, state: str | None = None) -> Flow:
    flow = Flow.from_client_config(
        _load_client_config(),
        scopes=GMAIL_SCOPES,
        state=state,
    )
    flow.redirect_uri = settings.google_redirect_uri
    return flow


def start_authorization() -> dict[str, str]:
    """Return Google consent URL + state for CSRF."""
    state = secrets.token_urlsafe(24)
    flow = _make_flow(state=state)
    auth_url, _ = flow.authorization_url(
        access_type="offline",
        prompt="consent",  # force refresh_token on re-connect
    )
    _pending_states.add(state)
    return {"authorization_url": auth_url, "state": state}


def finish_authorization(db: Session, *, code: str, state: str | None) -> GmailAccount:
    """Exchange auth code for tokens and upsert a GmailAccount row."""
    # Allow missing state after --reload; Google still returns a one-time code
    if state:
        _pending_states.discard(state)

    flow = _make_flow(state=state)
    try:
        flow.fetch_token(code=code)
    except Exception as exc:  # noqa: BLE001
        raise GmailAuthError(f"Token exchange failed: {exc}") from exc

    creds = flow.credentials
    if not creds or not creds.refresh_token:
        raise GmailAuthError(
            "Google did not return a refresh_token. Revoke this app at "
            "https://myaccount.google.com/permissions and connect again."
        )

    try:
        email = _email_from_creds(creds)
    except Exception as exc:  # noqa: BLE001
        raise GmailAuthError(f"Could not resolve account email: {exc}") from exc
    if not email:
        raise GmailAuthError("OAuth succeeded but could not resolve account email")

    return upsert_account(db, email=email, creds=creds)


def _email_from_id_token(token: str) -> str:
    """Decode email claim from OpenID id_token without an extra Google API call."""
    parts = token.split(".")
    if len(parts) < 2:
        return ""
    payload = parts[1]
    payload += "=" * (-len(payload) % 4)
    data = json.loads(base64.urlsafe_b64decode(payload.encode("utf-8")))
    return (data.get("email") or "").strip().lower()


def _email_from_creds(creds: Credentials) -> str:
    # Prefer id_token (local decode) — avoids slow/timeout userinfo round-trips
    id_tok = getattr(creds, "id_token", None)
    if id_tok:
        email = _email_from_id_token(id_tok)
        if email:
            return email

    # Fallback: lightweight userinfo GET with an explicit timeout
    import urllib.error
    import urllib.request

    req = urllib.request.Request(
        "https://www.googleapis.com/oauth2/v2/userinfo",
        headers={"Authorization": f"Bearer {creds.token}"},
    )
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            info = json.loads(resp.read().decode("utf-8"))
    except urllib.error.URLError as exc:
        raise GmailAuthError(f"userinfo request failed: {exc}") from exc
    return (info.get("email") or "").strip().lower()


def upsert_account(db: Session, *, email: str, creds: Credentials) -> GmailAccount:
    email = email.strip().lower()
    token_json = creds.to_json()
    scopes = " ".join(creds.scopes or GMAIL_SCOPES)

    row = db.query(GmailAccount).filter(GmailAccount.email == email).one_or_none()
    if row:
        row.token_json = token_json
        row.scopes = scopes
    else:
        make_default = db.query(GmailAccount).count() == 0
        row = GmailAccount(
            email=email,
            token_json=token_json,
            scopes=scopes,
            is_default=make_default,
        )
        db.add(row)

    db.commit()
    db.refresh(row)
    return row


def list_accounts(db: Session) -> list[GmailAccount]:
    return db.query(GmailAccount).order_by(GmailAccount.email).all()


def get_account(db: Session, email: str) -> GmailAccount | None:
    return (
        db.query(GmailAccount)
        .filter(GmailAccount.email == email.strip().lower())
        .one_or_none()
    )


def get_default_account(db: Session) -> GmailAccount | None:
    row = (
        db.query(GmailAccount)
        .filter(GmailAccount.is_default.is_(True))
        .one_or_none()
    )
    if row:
        return row
    return db.query(GmailAccount).order_by(GmailAccount.id).first()


def set_default_account(db: Session, email: str) -> GmailAccount:
    account = get_account(db, email)
    if not account:
        raise GmailAuthError(f"No connected Gmail account: {email}")
    for row in list_accounts(db):
        row.is_default = row.id == account.id
    db.commit()
    db.refresh(account)
    return account


def delete_account(db: Session, email: str) -> bool:
    account = get_account(db, email)
    if not account:
        return False
    was_default = account.is_default
    db.delete(account)
    db.commit()
    if was_default:
        nxt = db.query(GmailAccount).order_by(GmailAccount.id).first()
        if nxt:
            nxt.is_default = True
            db.commit()
    return True


def credentials_for(db: Session, account: GmailAccount) -> Credentials:
    creds = Credentials.from_authorized_user_info(
        json.loads(account.token_json),
        scopes=GMAIL_SCOPES,
    )
    if not creds.valid:
        if creds.expired and creds.refresh_token:
            try:
                creds.refresh(Request())
            except Exception as exc:  # noqa: BLE001
                raise GmailAuthError(
                    f"Failed to refresh Gmail token for {account.email}. "
                    f"Reconnect the account. ({exc})"
                ) from exc
            account.token_json = creds.to_json()
            db.add(account)
            # Flush only — do not commit here (caller may still mark FU done in same txn)
            db.flush()
        else:
            raise GmailAuthError(
                f"Gmail credentials for {account.email} are invalid. Reconnect the account."
            )
    return creds


def resolve_send_account(db: Session, from_address: str | None) -> GmailAccount | None:
    """Pick Gmail account for from_address, else default."""
    if from_address:
        account = get_account(db, from_address)
        if account:
            return account
    return get_default_account(db)


def send_message(db: Session, account: GmailAccount, msg: EmailMessage) -> str:
    """Send an EmailMessage via Gmail API as ``account``. Returns Gmail message id."""
    creds = credentials_for(db, account)
    raw = base64.urlsafe_b64encode(msg.as_bytes()).decode("utf-8")
    try:
        service = build(
            "gmail",
            "v1",
            http=_gmail_http(creds),
            cache_discovery=False,
        )
        result = (
            service.users()
            .messages()
            .send(userId="me", body={"raw": raw})
            .execute()
        )
    except HttpError as exc:
        raise GmailSendError(f"Gmail API error for {account.email}: {exc}") from exc
    except Exception as exc:  # noqa: BLE001
        raise GmailSendError(str(exc)) from exc

    return result.get("id") or ""


def account_has_readonly(account: GmailAccount) -> bool:
    scopes = (account.scopes or "").split()
    return GMAIL_READONLY_SCOPE in scopes or "https://mail.google.com/" in scopes


def _gmail_service(db: Session, account: GmailAccount):
    if not account_has_readonly(account):
        raise GmailAuthError(
            f"{account.email} is missing gmail.readonly — reconnect the account "
            "to enable inbox automation."
        )
    creds = credentials_for(db, account)
    return build(
        "gmail",
        "v1",
        http=_gmail_http(creds),
        cache_discovery=False,
    )


def list_recent_messages(
    db: Session,
    account: GmailAccount,
    *,
    query: str = "in:inbox newer_than:1d",
    max_results: int = 50,
) -> list[dict]:
    """Return lightweight message stubs: id, threadId."""
    try:
        service = _gmail_service(db, account)
        result = (
            service.users()
            .messages()
            .list(userId="me", q=query, maxResults=max_results)
            .execute()
        )
    except HttpError as exc:
        raise GmailAuthError(f"Gmail list failed for {account.email}: {exc}") from exc
    return result.get("messages") or []


def _header_map(payload: dict) -> dict[str, str]:
    headers = payload.get("headers") or []
    out: dict[str, str] = {}
    for h in headers:
        name = (h.get("name") or "").lower()
        if name:
            out[name] = h.get("value") or ""
    return out


def _decode_b64(data: str) -> str:
    if not data:
        return ""
    padded = data + "=" * (-len(data) % 4)
    try:
        return base64.urlsafe_b64decode(padded.encode("utf-8")).decode("utf-8", errors="replace")
    except Exception:  # noqa: BLE001
        return ""


def _walk_parts(payload: dict, *, prefer_html: bool = False) -> str:
    """Extract text/plain (preferred) or text/html from a Gmail message payload."""
    mime = (payload.get("mimeType") or "").lower()
    body = payload.get("body") or {}
    data = body.get("data")
    if data and mime.startswith("text/plain"):
        return _decode_b64(data)
    if data and prefer_html and mime.startswith("text/html"):
        return _decode_b64(data)

    texts: list[str] = []
    htmls: list[str] = []
    for part in payload.get("parts") or []:
        part_mime = (part.get("mimeType") or "").lower()
        if part.get("parts"):
            nested = _walk_parts(part, prefer_html=prefer_html)
            if nested:
                texts.append(nested)
            continue
        part_data = (part.get("body") or {}).get("data")
        if not part_data:
            continue
        decoded = _decode_b64(part_data)
        if part_mime.startswith("text/plain"):
            texts.append(decoded)
        elif part_mime.startswith("text/html"):
            htmls.append(decoded)
    if texts:
        return "\n".join(texts)
    if htmls:
        # crude strip tags
        import re

        return re.sub(r"<[^>]+>", " ", htmls[0])
    if data:
        return _decode_b64(data)
    return ""


def _parse_from(value: str) -> tuple[str, str]:
    """Return (display_name, email) from a From header."""
    import re

    value = (value or "").strip()
    m = re.match(r'"?([^"<]*)"?\s*<([^>]+)>', value)
    if m:
        return m.group(1).strip(), m.group(2).strip().lower()
    if "@" in value:
        return value.split("@", 1)[0], value.lower()
    return value, ""


def get_message_detail(db: Session, account: GmailAccount, message_id: str) -> dict:
    """Fetch full message: from, subject, text body, internalDate, threadId."""
    try:
        service = _gmail_service(db, account)
        msg = (
            service.users()
            .messages()
            .get(userId="me", id=message_id, format="full")
            .execute()
        )
    except HttpError as exc:
        raise GmailAuthError(
            f"Gmail get failed for {account.email}/{message_id}: {exc}"
        ) from exc

    payload = msg.get("payload") or {}
    headers = _header_map(payload)
    from_name, from_email = _parse_from(headers.get("from", ""))
    body = _walk_parts(payload)
    snippet = msg.get("snippet") or body[:400]
    return {
        "id": msg.get("id") or message_id,
        "thread_id": msg.get("threadId") or "",
        "from_name": from_name,
        "from_email": from_email,
        "subject": headers.get("subject") or "",
        "body": body,
        "snippet": snippet,
        "internal_date": int(msg.get("internalDate") or 0),
    }
