"""PDF screening report for a completed AI call — reuses the reports module's
stdlib PDF engine (no ReportLab in the offline venv). Long transcripts flow
across pages automatically."""

from apps.reports.pdf_builder import (
    CLASSIFICATION_COLORS, GREEN, INDIGO, LIGHT, MUTED, RED, SLATE, WHITE, PdfDoc,
)

from .models import AICall

REC_LABELS = {
    AICall.Recommendation.QUALIFIED: ("QUALIFIED", GREEN),
    AICall.Recommendation.REVIEW: ("NEEDS REVIEW", CLASSIFICATION_COLORS["Consider"]),
    AICall.Recommendation.NOT_QUALIFIED: ("NOT QUALIFIED", RED),
}


def _fmt_duration(seconds):
    if not seconds:
        return "-"
    m, s = divmod(int(seconds), 60)
    return f"{m}m {s:02d}s"


def render_call_report(call):
    cand = call.candidate
    job = call.job
    name = f"{cand.first_name} {cand.last_name}".strip()

    doc = PdfDoc(header_title="AI Screening Call Report")

    doc.spacer(6)
    doc.heading("AI Screening Report", None)
    doc.paragraph(f"{name}  -  {job.title}", font="F2", size=13, color=SLATE)
    doc.spacer(8)

    label, color = REC_LABELS.get(call.recommendation, ("PENDING", MUTED))
    doc.badge(label, color, size=11)
    doc.spacer(4)

    doc.heading("Candidate Information")
    doc.kv_table([
        ("Candidate", name),
        ("Email", cand.email or ""),
        ("Phone", cand.phone_number or ""),
        ("Experience", f"{cand.total_experience:g} years" if cand.total_experience else "Fresher"),
        ("Position", job.title),
        ("Client", job.client.name if job.client else "Internal"),
        ("Location", job.location or ""),
    ])

    doc.spacer(10)
    doc.heading("Call Details")
    doc.kv_table([
        ("Call Status", call.get_status_display()),
        ("Started", call.started_at.strftime("%d/%m/%Y %H:%M") if call.started_at else "-"),
        ("Ended", call.ended_at.strftime("%d/%m/%Y %H:%M") if call.ended_at else "-"),
        ("Duration", _fmt_duration(call.duration)),
        ("Attempts", str(call.attempts)),
        ("Provider Call ID", call.provider_call_id or "-"),
    ])

    doc.spacer(10)
    doc.heading("Screening Score")
    doc.score_bar("AI SCREENING SCORE", call.score or 0)

    if call.summary:
        doc.spacer(8)
        doc.heading("AI Summary")
        doc.paragraph(call.summary)

    doc.spacer(8)
    doc.heading("Call Transcript")
    if call.transcript:
        for line in call.transcript.split("\n"):
            line = line.strip()
            if not line:
                continue
            bold = line.startswith("Agent:") or line.startswith("[System]")
            doc.paragraph(line, font="F2" if bold else "F1", size=9,
                          color=INDIGO if line.startswith("Agent:") else SLATE)
    else:
        doc.paragraph("No transcript available for this call.", font="F3", color=MUTED)

    footer = (
        f"Generated by ATS System  ·  "
        f"{call.ended_at.strftime('%d/%m/%Y %H:%M') if call.ended_at else ''}  ·  TA-ATS 1.0"
    )
    return doc.to_bytes(footer_meta=footer)
