"""
scrylo/api/routers/leads.py
-----------------------------
Lead CRUD endpoints. Scraper (Week 3) and NLP (Week 5) write here.
Web UI (Week 2) and CLI display from here.
"""

from __future__ import annotations

from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from pydantic import BaseModel

from scrylo.db.models import Lead, LeadStatus
from scrylo.db.session import get_db

router = APIRouter(tags=["leads"])


# ── Pydantic schemas ──────────────────────────────────────────────────────
class LeadOut(BaseModel):
    id: int
    full_name: Optional[str]
    role: Optional[str]
    company: Optional[str]
    email: Optional[str]
    email_confidence: Optional[float]
    email_verified: bool
    icp_score: Optional[float]
    status: str
    source: Optional[str]

    model_config = {"from_attributes": True}


class LeadCreate(BaseModel):
    full_name: Optional[str] = None
    first_name: Optional[str] = None
    last_name: Optional[str] = None
    role: Optional[str] = None
    company: Optional[str] = None
    website: Optional[str] = None
    email: Optional[str] = None
    source: Optional[str] = None


import asyncio

# ── Routes ────────────────────────────────────────────────────────────────
@router.post("/leads", response_model=LeadOut, status_code=201)
async def create_lead(payload: LeadCreate, db: Session = Depends(get_db)):
    """Async wrapper for lead creation."""
    loop = asyncio.get_event_loop()
    def _create():
        lead = Lead(**payload.model_dump(exclude_none=True))
        db.add(lead)
        db.commit()
        db.refresh(lead)
        return lead
    return await loop.run_in_executor(None, _create)


@router.delete("/leads/{lead_id}", status_code=204)
async def delete_lead(lead_id: int, db: Session = Depends(get_db)):
    """Async wrapper for lead deletion."""
    loop = asyncio.get_event_loop()
    def _delete():
        lead = db.query(Lead).filter(Lead.id == lead_id).first()
        if not lead:
            raise HTTPException(status_code=404, detail="Lead not found")
        db.delete(lead)
        db.commit()
    await loop.run_in_executor(None, _delete)


@router.get("/leads/stats/summary")
async def leads_summary(db: Session = Depends(get_db)):
    """Quick stats for the Web UI dashboard header. Async to avoid event loop stalls."""
    loop = asyncio.get_event_loop()
    def _get_stats():
        total = db.query(Lead).count()
        enriched = db.query(Lead).filter(Lead.icp_score.isnot(None)).count()
        with_email = db.query(Lead).filter(Lead.email.isnot(None)).count()
        sent = db.query(Lead).filter(Lead.status == LeadStatus.SENT).count()
        opened = db.query(Lead).filter(Lead.status == LeadStatus.OPENED).count()
        return {
            "total": total,
            "enriched": enriched,
            "with_email": with_email,
            "sent": sent,
            "opened": opened,
            "open_rate": round(opened / sent * 100, 1) if sent else 0,
        }
    return await loop.run_in_executor(None, _get_stats)
