from fastapi import APIRouter, Depends, HTTPException, Request, status
from sqlalchemy.orm import Session

from app.automation.runner import run_task
from app.automation.tasks.login import HudlCredentials, LoginVerificationError, canonical_hudl_login_url
from app.core.auth_deps import require_auth
from app.core.database import get_db
from app.schemas.account_schema import (
    AccountCreateSchema,
    AccountIngestResponseSchema,
    AccountResponseSchema,
    AccountVerifySchema,
    HudlCredentialsSchema,
    PlaywrightVerificationSchema,
)
from app.services.account_service import (
    DEFAULT_HUDL_LOGIN_URL,
    create_account,
    get_account_by_account_id,
    get_active_account,
    resolve_account_fields,
    to_account_ingest_response,
    to_account_response,
    upsert_account,
)

router = APIRouter(dependencies=[Depends(require_auth)])


def _credentials_from_schema(
    credentials: HudlCredentialsSchema,
) -> tuple[HudlCredentials, str]:
    login_url = credentials.hudl_login_url or DEFAULT_HUDL_LOGIN_URL
    creds = HudlCredentials(
        email=credentials.hudl_email,
        password=credentials.hudl_password,
        login_url=login_url,
    )
    return creds, login_url


async def _run_playwright_verification(creds: HudlCredentials) -> dict:
    return await run_task("verify_credentials", credentials=creds)


def _http_error_from_verification(exc: Exception) -> HTTPException:
    if isinstance(exc, LoginVerificationError):
        return HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(exc),
        )
    if isinstance(exc, ValueError):
        return HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(exc),
        )
    return HTTPException(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        detail="Hudl credential verification failed",
    )


@router.post(
    "/accounts/verify",
    response_model=PlaywrightVerificationSchema,
    summary="Live Hudl verify (Playwright only, no save)",
)
async def verify_account_credentials(body: AccountVerifySchema):
   
    creds, _ = _credentials_from_schema(body.credentials)
    try:
        result = await _run_playwright_verification(creds)
    except (LoginVerificationError, ValueError) as exc:
        raise _http_error_from_verification(exc) from exc
    except Exception as exc:
        raise _http_error_from_verification(exc) from exc

    return PlaywrightVerificationSchema(**result)


@router.get(
    "/accounts/active",
    response_model=AccountResponseSchema | None,
    summary="Get the active stored Hudl account (no passwords)",
)
async def get_active_account_api(db: Session = Depends(get_db)):
    account = get_active_account(db)
    if not account:
        return None
    return to_account_response(account)


@router.post(
    "/accounts",
    response_model=AccountIngestResponseSchema,
    status_code=status.HTTP_201_CREATED,
    summary="Ingest account: validate, Playwright verify, encrypt & store",
)


async def ingest_account(
    body: AccountCreateSchema,
    request: Request,
    db: Session = Depends(get_db),
):
    
    account_id, name = resolve_account_fields(
        body.credentials.hudl_email,
        body.account_id,
        body.name,
    )

    creds, login_url = _credentials_from_schema(body.credentials)
    login_url = canonical_hudl_login_url(login_url)
    creds = HudlCredentials(
        email=creds.email,
        password=creds.password,
        login_url=login_url,
    )

    try:
        verification = await _run_playwright_verification(creds)
    except (LoginVerificationError, ValueError) as exc:
        raise _http_error_from_verification(exc) from exc
    except Exception as exc:
        raise _http_error_from_verification(exc) from exc

    metadata = None
    if body.metadata:
        metadata = body.metadata.model_dump(exclude_none=True)

    try:
        account = upsert_account(
            db,
            account_id=account_id,
            name=name,
            hudl_email=body.credentials.hudl_email,
            hudl_password=body.credentials.hudl_password,
            hudl_login_url=login_url,
            metadata=metadata,
        )
    except ValueError as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(exc),
        ) from exc

    return to_account_ingest_response(
        account,
        verification,
        request_host=request.url.hostname,
    )
