from __future__ import annotations

from typing import Any, Dict, List, Optional

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field

from .deps import require_api_key
from ...services.company_domain_promotions import record_promotions
from ...services.telemetry import emit

router = APIRouter(prefix="/api/v1/company-domains", tags=["Company Domains"])


class PromotionItem(BaseModel):
    name: str = Field(..., description="Company name as shown to the user")
    domain: str = Field(..., description="Promoted canonical domain")
    existing_domain: Optional[str] = Field(
        default=None, description="Original domain value before promotion"
    )
    match_confidence: Optional[float] = Field(
        default=None, ge=0.0, le=1.0, description="Confidence score (0-1 range)"
    )
    reason_chips: Optional[List[str]] = Field(
        default=None, description="Reason chips associated with the suggestion"
    )
    metadata: Optional[Dict[str, Any]] = Field(
        default=None, description="Arbitrary client metadata (sheet row, etc.)"
    )


class PromotionBatch(BaseModel):
    promotions: List[PromotionItem]


@router.post("/promote", status_code=202)
async def promote_company_domains(
    body: PromotionBatch, api_ctx=Depends(require_api_key)
) -> Dict[str, Any]:
    """
    Queue company-domain promotions for manual review.

    The request accepts a batch of promotion items submitted by the Sheets add-on.
    Each item captures the original domain, promoted suggestion, and optional context.
    """
    if not body.promotions:
        raise HTTPException(status_code=400, detail="No promotions provided")

    items = [p.dict() for p in body.promotions]
    try:
        saved = record_promotions(items, account_id=api_ctx.account_id, source="sheets")
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(
            status_code=500, detail=f"Failed to persist promotions: {exc}"
        ) from exc

    emit(
        "company_domain.promoted",
        account_id=api_ctx.account_id,
        promotions=saved,
        total=len(body.promotions),
    )

    return {"status": "accepted", "promotions_saved": saved}
