"""Reports — panelist notes + evaluation PDF generation."""

from __future__ import annotations

import base64
import io
import json
import os
from pathlib import Path
from uuid import uuid4
from xml.sax.saxutils import escape

from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.platypus import (
    HRFlowable,
    KeepTogether,
    Paragraph,
    SimpleDocTemplate,
    Spacer,
    Table,
    TableStyle,
)

from app.schemas.common import JobStatus
from app.schemas.reports import (
    EvaluationReportRequest,
    EvaluationReportResponse,
    PanelistNotesRequest,
    PanelistNotesResponse,
    StructuredEvaluationReport,
)
from app.services.reports.evaluation_report_builder import (
    build_structured_evaluation_report,
    structured_report_to_markdown,
)
from app.services.shared.ai_generate import generate_json

# Persistent local directory for generated evaluation PDFs.
_REPO_ROOT = Path(__file__).resolve().parents[3]
_reports_env = os.getenv("REPORTS_DIR", ".data/reports")
REPORTS_DIR = Path(_reports_env)
if not REPORTS_DIR.is_absolute():
    REPORTS_DIR = (_REPO_ROOT / REPORTS_DIR).resolve()
REPORTS_DIR.mkdir(parents=True, exist_ok=True)

_NAVY = colors.HexColor("#17365D")
_LIGHT = colors.HexColor("#F4F7FB")
_BORDER = colors.HexColor("#D0D7E2")


def _format_value(value) -> str:
    if value is None:
        return "Not provided"
    if isinstance(value, (dict, list)):
        return json.dumps(value, indent=2, ensure_ascii=False, default=str)
    return str(value)


def _p(text: str, style) -> Paragraph:
    return Paragraph(escape(text).replace("\n", "<br/>"), style)


def _section_heading(title: str, styles) -> list:
    return [
        Spacer(1, 8),
        Paragraph(escape(title), styles["SectionHeading"]),
        HRFlowable(
            width="100%",
            thickness=0.6,
            color=_BORDER,
            spaceBefore=2,
            spaceAfter=8,
        ),
    ]


def _bullet_list(items: list[str], styles) -> list:
    """Plain • paragraphs — avoids ReportLab ListItem printing 'bullet' literally."""
    if not items:
        return [_p("None stored.", styles["SmallBody"])]
    out: list = []
    for item in items:
        out.append(
            Paragraph(
                # Use plain hyphen — Helvetica has no reliable • glyph
                f"- {escape(item)}",
                styles["BulletItem"],
            )
        )
    return out


def generate_evaluation_pdf_from_structured(
    *,
    report: StructuredEvaluationReport,
    report_id: str,
) -> bytes:
    """Render a clean, sectioned PDF from structured report JSON (no LLM)."""
    buffer = io.BytesIO()
    document = SimpleDocTemplate(
        buffer,
        pagesize=A4,
        rightMargin=16 * mm,
        leftMargin=16 * mm,
        topMargin=16 * mm,
        bottomMargin=16 * mm,
        title=report.report_title,
        author="AI Interviewer Pro",
    )

    styles = getSampleStyleSheet()
    styles.add(
        ParagraphStyle(
            name="ReportTitle",
            parent=styles["Title"],
            alignment=TA_CENTER,
            textColor=_NAVY,
            fontSize=18,
            leading=22,
            spaceAfter=4,
        )
    )
    styles.add(
        ParagraphStyle(
            name="ReportSubtitle",
            parent=styles["Normal"],
            alignment=TA_CENTER,
            textColor=_NAVY,
            fontSize=11,
            leading=14,
            spaceAfter=10,
        )
    )
    styles.add(
        ParagraphStyle(
            name="SectionHeading",
            parent=styles["Heading2"],
            textColor=_NAVY,
            fontSize=12,
            leading=15,
            spaceBefore=4,
            spaceAfter=2,
            keepWithNext=True,
        )
    )
    styles.add(
        ParagraphStyle(
            name="MetaLabel",
            parent=styles["Normal"],
            fontSize=9,
            leading=12,
            textColor=colors.HexColor("#445566"),
        )
    )
    styles.add(
        ParagraphStyle(
            name="QTitle",
            parent=styles["Normal"],
            fontSize=10,
            leading=13,
            textColor=_NAVY,
            spaceBefore=2,
            spaceAfter=2,
        )
    )
    styles.add(
        ParagraphStyle(
            name="SmallBody",
            parent=styles["Normal"],
            fontSize=9,
            leading=12,
            alignment=TA_LEFT,
        )
    )
    styles.add(
        ParagraphStyle(
            name="FooterNote",
            parent=styles["Normal"],
            fontSize=8,
            leading=10,
            textColor=colors.grey,
            spaceBefore=10,
        )
    )
    styles.add(
        ParagraphStyle(
            name="BulletItem",
            parent=styles["Normal"],
            fontSize=9,
            leading=13,
            leftIndent=10,
            spaceBefore=1,
            spaceAfter=2,
        )
    )

    info = report.candidate_interview
    overall = report.overall
    story: list = [
        Paragraph("AI INTERVIEWER PRO", styles["ReportTitle"]),
        Paragraph(escape(report.report_title), styles["ReportSubtitle"]),
        HRFlowable(width="100%", thickness=1.2, color=_NAVY, spaceAfter=10),
    ]

    # --- Candidate & Interview Information ---
    story.extend(_section_heading("1. Candidate & Interview Information", styles))
    meta_rows = [
        ["Candidate", f"{info.candidate_name} ({info.candidate_id})"],
        ["Interview ID", info.interview_id],
        ["Role", info.role_title or "Not provided"],
        ["Company", info.company_name or "Not provided"],
        ["Mode", (info.interview_mode or "n/a").title()],
        ["Report ID", report_id],
    ]
    if info.evaluation_id:
        meta_rows.insert(2, ["Evaluation ID", info.evaluation_id])
    if info.evaluation_version is not None:
        meta_rows.append(["Evaluation version", str(info.evaluation_version)])
    meta_table = Table(
        [[_p(a, styles["MetaLabel"]), _p(b, styles["SmallBody"])] for a, b in meta_rows],
        colWidths=[40 * mm, 130 * mm],
    )
    meta_table.setStyle(
        TableStyle(
            [
                ("BACKGROUND", (0, 0), (0, -1), _LIGHT),
                ("BOX", (0, 0), (-1, -1), 0.4, _BORDER),
                ("INNERGRID", (0, 0), (-1, -1), 0.3, _BORDER),
                ("VALIGN", (0, 0), (-1, -1), "TOP"),
                ("LEFTPADDING", (0, 0), (-1, -1), 6),
                ("RIGHTPADDING", (0, 0), (-1, -1), 6),
                ("TOPPADDING", (0, 0), (-1, -1), 4),
                ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
            ]
        )
    )
    story.append(meta_table)

    # --- Overall Score and Hiring Recommendation ---
    story.extend(_section_heading("2. Overall Score and Hiring Recommendation", styles))
    score_s = (
        f"{overall.overall_score:.2f}"
        if overall.overall_score is not None
        else "Not available"
    )
    overall_rows = [
        ["Overall score", score_s],
        ["Recommendation", overall.recommendation_label or "Not available"],
    ]
    if overall.recommendation_action:
        overall_rows.append(["Action", overall.recommendation_action])
    if overall.recommendation_reason:
        overall_rows.append(["Reason", overall.recommendation_reason])
    overall_table = Table(
        [
            [_p(a, styles["MetaLabel"]), _p(b, styles["SmallBody"])]
            for a, b in overall_rows
        ],
        colWidths=[40 * mm, 130 * mm],
    )
    overall_table.setStyle(
        TableStyle(
            [
                ("BACKGROUND", (0, 0), (0, -1), _LIGHT),
                ("BOX", (0, 0), (-1, -1), 0.4, _BORDER),
                ("INNERGRID", (0, 0), (-1, -1), 0.3, _BORDER),
                ("VALIGN", (0, 0), (-1, -1), "TOP"),
                ("LEFTPADDING", (0, 0), (-1, -1), 6),
                ("RIGHTPADDING", (0, 0), (-1, -1), 6),
                ("TOPPADDING", (0, 0), (-1, -1), 4),
                ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
            ]
        )
    )
    story.append(overall_table)
    if overall.summary:
        story.append(Spacer(1, 6))
        story.append(_p(overall.summary, styles["SmallBody"]))

    # --- Competency-wise Scores ---
    story.extend(_section_heading("3. Competency-wise Scores", styles))
    if report.competency_scores:
        comp_data = [[_p("Competency", styles["MetaLabel"]), _p("Score", styles["MetaLabel"])]]
        for c in report.competency_scores:
            score_cell = f"{c.score:.2f}" if c.score is not None else "n/a"
            comp_data.append(
                [_p(c.label, styles["SmallBody"]), _p(score_cell, styles["SmallBody"])]
            )
        comp_table = Table(comp_data, colWidths=[130 * mm, 40 * mm])
        comp_table.setStyle(
            TableStyle(
                [
                    ("BACKGROUND", (0, 0), (-1, 0), _LIGHT),
                    ("BOX", (0, 0), (-1, -1), 0.4, _BORDER),
                    ("INNERGRID", (0, 0), (-1, -1), 0.3, _BORDER),
                    ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
                    ("LEFTPADDING", (0, 0), (-1, -1), 6),
                    ("RIGHTPADDING", (0, 0), (-1, -1), 6),
                    ("TOPPADDING", (0, 0), (-1, -1), 4),
                    ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
                ]
            )
        )
        story.append(comp_table)
    else:
        story.append(_p("None stored.", styles["SmallBody"]))

    # --- Question-wise Evaluation ---
    story.extend(_section_heading("4. Question-wise Evaluation", styles))
    if report.question_evaluations:
        for i, q in enumerate(report.question_evaluations, start=1):
            score_s = f"{q.score:.2f}" if q.score is not None else "n/a"
            band = f" ({q.score_band})" if q.score_band else ""
            block = [
                Paragraph(
                    f"<b>Q{i}.</b> {escape(q.question)}",
                    styles["QTitle"],
                ),
                _p(f"Score: {score_s}{band}", styles["MetaLabel"]),
            ]
            if q.candidate_answer:
                block.append(_p(f"Answer: {q.candidate_answer}", styles["SmallBody"]))
            if q.feedback:
                block.append(_p(f"Feedback: {q.feedback}", styles["SmallBody"]))
            block.append(Spacer(1, 6))
            story.append(KeepTogether(block))
    else:
        story.append(_p("None stored.", styles["SmallBody"]))

    # --- Key Strengths ---
    story.extend(_section_heading("5. Key Strengths", styles))
    story.extend(_bullet_list(report.key_strengths, styles))

    # --- Areas of Improvement ---
    story.extend(_section_heading("6. Areas of Improvement", styles))
    story.extend(_bullet_list(report.areas_of_improvement, styles))

    # --- Final Recommendation ---
    story.extend(_section_heading("7. Final Recommendation", styles))
    fr = report.final_recommendation
    if fr.label:
        final_line = fr.label
        if fr.action:
            final_line += f" · {fr.action}"
        story.append(_p(final_line, styles["QTitle"]))
        if fr.reason:
            story.append(_p(fr.reason, styles["SmallBody"]))
    else:
        story.append(_p("Not available", styles["SmallBody"]))
    story.append(_p(fr.note, styles["FooterNote"]))

    def add_page_number(canvas, doc):
        canvas.saveState()
        canvas.setFont("Helvetica", 8)
        canvas.setFillColor(colors.grey)
        canvas.drawCentredString(
            A4[0] / 2,
            10 * mm,
            f"AI Interviewer Pro | Page {doc.page}",
        )
        canvas.restoreState()

    document.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number)
    pdf_bytes = buffer.getvalue()
    buffer.close()
    if not pdf_bytes.startswith(b"%PDF-"):
        raise RuntimeError("Generated report is not a valid PDF.")
    return pdf_bytes


# Backward-compatible alias used by older imports/tests
def generate_evaluation_pdf(
    *,
    summary_markdown: str,
    candidate_name: str,
    role_title: str,
    company_name: str | None,
    report_id: str,
) -> bytes:
    """Legacy wrapper — prefer generate_evaluation_pdf_from_structured."""
    # Minimal structured shell so old callers still get a PDF
    report = StructuredEvaluationReport.model_validate(
        {
            "report_title": "Interview Evaluation",
            "candidate_interview": {
                "candidate_id": "n/a",
                "candidate_name": candidate_name,
                "interview_id": "n/a",
                "role_title": role_title,
                "company_name": company_name,
            },
            "overall": {"summary": summary_markdown},
            "final_recommendation": {},
        }
    )
    return generate_evaluation_pdf_from_structured(
        report=report, report_id=report_id
    )


class ReportsService:
    async def panelist_notes(
        self,
        payload: PanelistNotesRequest,
    ) -> PanelistNotesResponse:
        system = (
            "Write structured panelist notes based only on the "
            "provided evidence. Do not invent candidate qualifications "
            "or interview observations. Return JSON with keys: "
            "notes_markdown, highlights (array), risks (array), "
            "recommendation."
        )

        user = (
            f"Role: {payload.role_title}\n"
            f"Candidate: {payload.candidate_id}\n"
            f"Scorecard: {_format_value(payload.scorecard)}\n"
            f"Transcript excerpt: "
            f"{_format_value(payload.transcript_excerpt)}\n"
            f"Recruiter annotations: "
            f"{_format_value(payload.recruiter_annotations)}"
        )

        def local() -> dict:
            return {
                "notes_markdown": (
                    f"## Panelist notes — {payload.role_title}\n\n"
                    f"- Candidate `{payload.candidate_id}`.\n"
                    "- Review the scorecard and transcript evidence.\n"
                    "- Follow up on measurable project impact and "
                    "role-specific competencies."
                ),
                "highlights": [],
                "risks": [
                    "Further validation may be required."
                ],
                "recommendation": "review_required",
            }

        data, stub, provider = await generate_json(
            system=system,
            user=user,
            local_factory=local,
        )

        notes_markdown = data.get("notes_markdown")
        if not isinstance(notes_markdown, str) or not notes_markdown.strip():
            fallback = local()
            notes_markdown = fallback["notes_markdown"]
            stub = True

        highlights = data.get("highlights")
        risks = data.get("risks")

        return PanelistNotesResponse(
            correlation_id=payload.correlation_id,
            interview_id=payload.interview_id,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Panelist notes via {provider}",
            notes_markdown=notes_markdown,
            highlights=highlights if isinstance(highlights, list) else [],
            risks=risks if isinstance(risks, list) else [],
            recommendation=data.get("recommendation"),
        )

    async def evaluation_pdf(
        self,
        payload: EvaluationReportRequest,
    ) -> EvaluationReportResponse:
        """Deterministic structured JSON + PDF from a completed evaluation row."""
        from fastapi import HTTPException

        from app.services.interviews.evaluation_store import get_by_candidate_interview

        row = get_by_candidate_interview(payload.candidate_id, payload.interview_id)
        if row is None:
            raise HTTPException(
                status_code=404,
                detail=(
                    "No evaluation found for this candidate_id + interview_id. "
                    "Run POST /interviews/final-evaluation first."
                ),
            )
        if (row.evaluation_status or "") != "completed":
            raise HTTPException(
                status_code=409,
                detail=(
                    f"Evaluation is not completed (status={row.evaluation_status!r}). "
                    "PDF is only generated from successfully saved evaluations."
                ),
            )

        candidate_name = payload.candidate_name or payload.candidate_id
        report = build_structured_evaluation_report(
            candidate_id=row.candidate_id,
            candidate_name=str(candidate_name),
            interview_id=row.interview_id,
            evaluation_id=row.evaluation_id,
            interview_mode=row.interview_mode,
            role_title=row.role_title or "",
            company_name=row.company_name,
            evaluation_version=int(row.evaluation_version or 1),
            overall_score=row.overall_score,
            evaluation_summary=row.evaluation_summary or "",
            strengths=list(row.strengths or []),
            improvement_areas=list(row.improvement_areas or []),
            competency_scores=list(row.competency_scores or []),
            question_evaluations=list(row.question_evaluations or []),
            final_recommendation=dict(row.final_recommendation or {}),
        )
        summary_markdown = structured_report_to_markdown(report)

        report_id = str(uuid4())
        pdf_bytes = generate_evaluation_pdf_from_structured(
            report=report,
            report_id=report_id,
        )

        pdf_path = REPORTS_DIR / f"{report_id}.pdf"
        pdf_path.write_bytes(pdf_bytes)

        try:
            from app.persistence import resolve_persist_backend
            from app.services.reports.report_db import upsert_report

            if resolve_persist_backend() in {"postgres", "dual"}:
                upsert_report(
                    report_id=report_id,
                    storage_path=str(pdf_path.resolve()),
                    interview_id=str(row.interview_id),
                    summary_markdown=summary_markdown,
                    candidate_name=str(candidate_name),
                    role_title=str(row.role_title or ""),
                    company_name=(
                        str(row.company_name) if row.company_name else None
                    ),
                )
        except Exception:  # noqa: BLE001
            import logging

            logging.getLogger(__name__).warning(
                "Failed to persist report metadata %s", report_id, exc_info=True
            )

        pdf_base64 = base64.b64encode(pdf_bytes).decode("ascii")
        download_url = f"/api/v1/reports/{report_id}/download"

        return EvaluationReportResponse(
            correlation_id=payload.correlation_id,
            interview_id=row.interview_id,
            candidate_id=row.candidate_id,
            evaluation_id=row.evaluation_id,
            report_id=report_id,
            status=JobStatus.SUCCEEDED,
            stub=False,
            message=(
                "Structured evaluation report generated from saved evaluation "
                "(deterministic; no LLM)"
            ),
            pdf_base64=pdf_base64,
            download_url=download_url,
            summary_markdown=summary_markdown,
            report=report,
        )
