"""Gmail account management endpoints."""
import secrets
from datetime import datetime, timezone

from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_current_user, get_db, require_csrf
from app.core.security import log_audit
from app.models import GmailAccount, OAuthClientConfig, OAuthToken, User
from app.services import gmail_service

router = APIRouter(prefix="/gmail", tags=["gmail-accounts"])


class AccountUpdate(BaseModel):
    sending_method: str = "api"     # api | smtp
    daily_limit: int = 200
    campaign_limit: int = 200


def _account_out(account: GmailAccount) -> dict:
    t = account.oauth_token
    return {
        "id": account.id,
        "email": account.email,
        "display_name": account.display_name,
        "status": account.status,
        "sending_method": account.sending_method,
        "daily_limit": account.daily_limit,
        "campaign_limit": account.campaign_limit,
        "sends_today": account.sends_today,
        "last_success_at": account.last_success_at.isoformat() if account.last_success_at else None,
        "error_count": account.error_count,
        "last_error": (account.last_error or "")[:300],
        "cooldown_until": account.cooldown_until.isoformat() if account.cooldown_until else None,
        "has_refresh_token": bool(t and t.refresh_token_enc),
        "token_expires_at": t.expires_at.isoformat() if t and t.expires_at else None,
        "authorized": account.status == "authorized",
    }


@router.get("/accounts")
async def list_accounts(user: User = Depends(get_current_user),
                        db: AsyncSession = Depends(get_db)):
    rows = (await db.execute(select(GmailAccount).where(
        GmailAccount.user_id == user.id).order_by(GmailAccount.id))).scalars().all()
    return {"accounts": [_account_out(a) for a in rows], "count": len(rows)}


@router.post("/accounts/connect")
async def connect_start(user: User = Depends(get_current_user),
                        db: AsyncSession = Depends(get_db)):
    """Return the Google authorization URL for this user to open (real OAuth start)."""
    try:
        gmail_service.resolve_client_config()
    except gmail_service.GmailOauthError:
        raise HTTPException(400, "No Google OAuth client configuration imported yet. "
                                 "Use 'Import Gmail Configuration' first.")
    from app.api.routers.auth import google_start_impl
    return await google_start_impl(user)


@router.post("/accounts/{account_id}/test")
async def test_account(account_id: int, user: User = Depends(get_current_user),
                       db: AsyncSession = Depends(get_db)):
    """Real connection test: verify OAuth creds and Gmail API profile."""
    account = await db.get(GmailAccount, account_id)
    if not account or account.user_id != user.id:
        raise HTTPException(404, "Account not found")
    token = account.oauth_token
    if not token:
        return {"ok": False, "detail": "No OAuth token stored for this account"}
    from app.db.session import SyncSession
    with SyncSession() as s:
        acc_sync = s.get(GmailAccount, account.id)
        tok_sync = s.get(OAuthToken, token.id)
        try:
            client = gmail_service.build_gmail_client_from_account(acc_sync, tok_sync)
            result = client.verify_connection()
        except Exception as e:
            result = {"ok": False, "detail": str(e)[:400]}
    if result.get("ok"):
        account.status = "authorized"
        await db.commit()
    else:
        account.status = "expired" if "auth" in (result.get("detail") or "").lower() else account.status
        account.last_error = (result.get("detail") or "")[:500]
        await db.commit()
    await log_audit(db, user.id, "gmail.test", "gmail_account", account.id,
                    {"ok": result.get("ok")}, None)
    return result


@router.post("/accounts/{account_id}/reauthorize")
async def reauthorize(account_id: int, user: User = Depends(get_current_user),
                      db: AsyncSession = Depends(get_db)):
    account = await db.get(GmailAccount, account_id)
