"""Build structured interview evaluation reports from saved DB rows (no LLM)."""

from __future__ import annotations

import re
from typing import Any

from app.schemas.reports import (
    CandidateInterviewInfo,
    CompetencyScoreItem,
    FinalRecommendationBlock,
    OverallScoreRecommendation,
    QuestionEvaluationItem,
    StructuredEvaluationReport,
)

_WS = re.compile(r"\s+")
_MAX_FEEDBACK = 420
_MAX_ANSWER = 800
_MAX_SUMMARY = 600
_MAX_BULLET = 220


def _clean_text(value: Any, *, max_len: int | None = None) -> str | None:
    if value is None:
        return None
    text = _WS.sub(" ", str(value)).strip()
    if not text:
        return None
    if max_len is not None and len(text) > max_len:
        text = text[: max_len - 1].rstrip() + "…"
    return text


def _dedupe_bullets(items: list[Any], *, limit: int = 8) -> list[str]:
    seen: set[str] = set()
    out: list[str] = []
    for raw in items or []:
        text = _clean_text(raw, max_len=_MAX_BULLET)
        if not text:
            continue
        key = text.lower()
        if key in seen:
            continue
        seen.add(key)
        out.append(text)
        if len(out) >= limit:
            break
    return out


def _score(value: Any) -> float | None:
    if value is None:
        return None
    try:
        return float(value)
    except (TypeError, ValueError):
        return None


def _mode_title(mode: str | None) -> str:
    key = (mode or "text").strip().lower()
    return {
        "text": "Text Interview Evaluation",
        "voice": "Voice Interview Evaluation",
        "video": "Video Interview Evaluation",
    }.get(key, "Interview Evaluation")


def _competency_items(raw: list[Any]) -> list[CompetencyScoreItem]:
    out: list[CompetencyScoreItem] = []
    seen: set[str] = set()
    for row in raw or []:
        if not isinstance(row, dict):
            continue
        label = _clean_text(row.get("label") or row.get("key")) or "Competency"
        key = _clean_text(row.get("key")) or label.lower().replace(" ", "_")
        dedupe = key.lower()
        if dedupe in seen:
            continue
        seen.add(dedupe)
        out.append(
            CompetencyScoreItem(
                key=key,
                label=label,
                score=_score(row.get("score")),
            )
        )
    return out


def _question_items(raw: list[Any]) -> list[QuestionEvaluationItem]:
    out: list[QuestionEvaluationItem] = []
    for i, row in enumerate(raw or [], start=1):
        if not isinstance(row, dict):
            continue
        question = _clean_text(
            row.get("question") or row.get("question_text") or f"Question {i}"
        )
        if not question:
            continue
        feedback = _clean_text(
            row.get("feedback")
            or row.get("ai_explanation")
            or row.get("explanation"),
            max_len=_MAX_FEEDBACK,
        )
        turn = row.get("turn_index")
        try:
            turn_i = int(turn) if turn is not None else i - 1
        except (TypeError, ValueError):
            turn_i = i - 1
        out.append(
            QuestionEvaluationItem(
                question_id=_clean_text(row.get("question_id")),
                turn_index=turn_i,
                question=question,
                candidate_answer=_clean_text(
                    row.get("candidate_answer")
                    or row.get("answer")
                    or row.get("response"),
                    max_len=_MAX_ANSWER,
                ),
                score=_score(row.get("score")),
                score_band=_clean_text(row.get("score_band")),
                feedback=feedback,
            )
        )
    return out


def build_structured_evaluation_report(
    *,
    candidate_id: str,
    candidate_name: str,
    interview_id: str,
    evaluation_id: str | None,
    interview_mode: str | None,
    role_title: str | None,
    company_name: str | None,
    evaluation_version: int | None,
    overall_score: float | None,
    evaluation_summary: str | None,
    strengths: list[Any],
    improvement_areas: list[Any],
    competency_scores: list[Any],
    question_evaluations: list[Any],
    final_recommendation: dict[str, Any] | None,
) -> StructuredEvaluationReport:
    """Map a saved interview_evaluations row → structured report (no invention)."""
    rec = dict(final_recommendation or {})
    label = _clean_text(rec.get("label"))
    action = _clean_text(rec.get("action"))
    reason = _clean_text(rec.get("reason"), max_len=_MAX_FEEDBACK)
    requires = rec.get("requires_human_review")
    if not isinstance(requires, bool):
        requires = True if label else None

    summary = _clean_text(evaluation_summary, max_len=_MAX_SUMMARY)
    # Avoid repeating the recommendation reason as the summary when identical
    if summary and reason and summary.lower() == reason.lower():
        summary = None

    return StructuredEvaluationReport(
        report_title=_mode_title(interview_mode),
        candidate_interview=CandidateInterviewInfo(
            candidate_id=candidate_id,
            candidate_name=candidate_name,
            interview_id=interview_id,
            evaluation_id=evaluation_id,
            interview_mode=(interview_mode or None),
            role_title=_clean_text(role_title),
            company_name=_clean_text(company_name),
            evaluation_version=evaluation_version,
        ),
        overall=OverallScoreRecommendation(
            overall_score=_score(overall_score),
            summary=summary,
            recommendation_label=label,
            recommendation_action=action,
            recommendation_reason=reason,
        ),
        competency_scores=_competency_items(list(competency_scores or [])),
        question_evaluations=_question_items(list(question_evaluations or [])),
        key_strengths=_dedupe_bullets(list(strengths or [])),
        areas_of_improvement=_dedupe_bullets(list(improvement_areas or [])),
        final_recommendation=FinalRecommendationBlock(
            label=label,
            action=action,
            reason=reason,
            requires_human_review=requires,
        ),
    )


def structured_report_to_markdown(report: StructuredEvaluationReport) -> str:
    """Compact markdown for clients that still read `summary_markdown`."""
    info = report.candidate_interview
    overall = report.overall
    lines: list[str] = [
        f"# {report.report_title}",
        "",
        "## Candidate & Interview Information",
        f"- **Candidate:** {info.candidate_name} (`{info.candidate_id}`)",
        f"- **Interview ID:** {info.interview_id}",
        f"- **Role:** {info.role_title or 'Not provided'}",
        f"- **Company:** {info.company_name or 'Not provided'}",
    ]
    if info.evaluation_version is not None:
        lines.append(f"- **Evaluation version:** {info.evaluation_version}")
    lines.extend(["", "## Overall Score and Hiring Recommendation"])
    if overall.overall_score is not None:
        lines.append(f"- **Overall score:** {overall.overall_score:.2f}")
    else:
        lines.append("- **Overall score:** Not available")
    if overall.recommendation_label:
        lines.append(f"- **Recommendation:** {overall.recommendation_label}")
    if overall.recommendation_action:
        lines.append(f"- **Action:** {overall.recommendation_action}")
    if overall.recommendation_reason:
        lines.append(f"- **Reason:** {overall.recommendation_reason}")
    if overall.summary:
        lines.extend(["", overall.summary])

    lines.extend(["", "## Competency-wise Scores"])
    if report.competency_scores:
        for c in report.competency_scores:
            score_s = f"{c.score:.2f}" if c.score is not None else "n/a"
            lines.append(f"- **{c.label}:** {score_s}")
    else:
        lines.append("- None stored")

    lines.extend(["", "## Question-wise Evaluation"])
    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"
            lines.append(f"### Q{i}. {q.question}")
            lines.append(f"- **Score:** {score_s}")
            if q.candidate_answer:
                lines.append(f"- **Answer:** {q.candidate_answer}")
            if q.feedback:
                lines.append(f"- **Feedback:** {q.feedback}")
            lines.append("")
    else:
        lines.append("- None stored")
        lines.append("")

    lines.extend(["## Key Strengths"])
    if report.key_strengths:
        lines.extend(f"- {s}" for s in report.key_strengths)
    else:
        lines.append("- None stored")

    lines.extend(["", "## Areas of Improvement"])
    if report.areas_of_improvement:
        lines.extend(f"- {s}" for s in report.areas_of_improvement)
    else:
        lines.append("- None stored")

    fr = report.final_recommendation
    lines.extend(["", "## Final Recommendation"])
    if fr.label:
        line = f"**{fr.label}**"
        if fr.reason:
            line += f" — {fr.reason}"
        lines.append(line)
    else:
        lines.append("Not available")
    lines.extend(["", f"_{fr.note}_", ""])
    return "\n".join(lines)
