"""Badge recommendations from performance signals."""

from __future__ import annotations

from typing import Any

from app.schemas.badges import BadgeItem, BadgeRecommendRequest, BadgeRecommendResponse
from app.schemas.common import JobStatus
from app.services.shared.ai_generate import generate_json


def _as_score(value: Any) -> float | None:
    if isinstance(value, bool):
        return None
    if isinstance(value, (int, float)):
        return max(0.0, min(1.0, float(value)))
    if isinstance(value, str):
        try:
            return max(0.0, min(1.0, float(value.strip())))
        except ValueError:
            return None
    return None


def _scores_from_rows(rows: list[dict[str, Any]]) -> list[float]:
    out: list[float] = []
    for row in rows:
        if not isinstance(row, dict):
            continue
        for key in (
            "score",
            "overall_score",
            "overall",
            "percent",
            "percentage",
            "result_score",
        ):
            raw = row.get(key)
            if key in {"percent", "percentage"} and isinstance(raw, (int, float)):
                # Allow 0–100 style percentages
                s = _as_score(float(raw) / 100.0 if float(raw) > 1.0 else raw)
            else:
                s = _as_score(raw)
            if s is not None:
                out.append(s)
                break
    return out


def _local_recommendations(payload: BadgeRecommendRequest) -> dict[str, list[dict]]:
    """Deterministic badges from available track/assessment/interview signals."""
    earned: list[dict[str, Any]] = []
    next_badges: list[dict[str, Any]] = []

    interview_scores = _scores_from_rows(
        [r for r in payload.interview_scores if isinstance(r, dict)]
    )
    assessment_scores = _scores_from_rows(
        [r for r in payload.assessment_results if isinstance(r, dict)]
    )
    track_passes = 0
    for row in payload.track_results:
        if not isinstance(row, dict):
            continue
        status = str(row.get("status") or row.get("result") or "").lower()
        completed = row.get("completed") is True or status in {
            "completed",
            "passed",
            "done",
            "success",
        }
        score = None
        for key in ("score", "overall_score", "pass_score"):
            score = _as_score(row.get(key))
            if score is not None:
                break
        if completed or (score is not None and score >= 0.6):
            track_passes += 1

    if track_passes:
        earned.append(
            {
                "badge_id": "track-starter",
                "name": "Track Starter",
                "level": "beginner",
                "reason": f"Completed {track_passes} interview track attempt(s)",
            }
        )
        if track_passes >= 3:
            earned.append(
                {
                    "badge_id": "track-finisher",
                    "name": "Track Finisher",
                    "level": "intermediate",
                    "reason": "Completed 3+ interview tracks",
                }
            )
        else:
            next_badges.append(
                {
                    "badge_id": "track-finisher",
                    "name": "Track Finisher",
                    "level": "intermediate",
                    "reason": "Complete 3 interview tracks",
                }
            )

    if assessment_scores:
        best_a = max(assessment_scores)
        if best_a >= 0.7:
            earned.append(
                {
                    "badge_id": "assessment-ace",
                    "name": "Assessment Ace",
                    "level": "intermediate",
                    "reason": f"Assessment score {best_a:.2f} (≥ 0.70)",
                }
            )
        else:
            next_badges.append(
                {
                    "badge_id": "assessment-ace",
                    "name": "Assessment Ace",
                    "level": "intermediate",
                    "reason": "Score 70%+ on an assessment",
                }
            )
    else:
        next_badges.append(
            {
                "badge_id": "assessment-ace",
                "name": "Assessment Ace",
                "level": "intermediate",
                "reason": "Pass an assessment above 70%",
            }
        )

    if interview_scores:
        best_i = max(interview_scores)
        avg_i = sum(interview_scores) / len(interview_scores)
        if best_i >= 0.8:
            earned.append(
                {
                    "badge_id": "strong-interviewee",
                    "name": "Strong Interviewee",
                    "level": "advanced",
                    "reason": f"Interview score {best_i:.2f} (≥ 0.80)",
                }
            )
        elif best_i >= 0.6:
            earned.append(
                {
                    "badge_id": "solid-interview",
                    "name": "Solid Interview",
                    "level": "intermediate",
                    "reason": f"Interview score {best_i:.2f} (≥ 0.60)",
                }
            )
            next_badges.append(
                {
                    "badge_id": "strong-interviewee",
                    "name": "Strong Interviewee",
                    "level": "advanced",
                    "reason": "Reach an interview score ≥ 0.80",
                }
            )
        else:
            next_badges.append(
                {
                    "badge_id": "solid-interview",
                    "name": "Solid Interview",
                    "level": "intermediate",
                    "reason": "Reach an interview score ≥ 0.60",
                }
            )
        if avg_i >= 0.75 and len(interview_scores) >= 2:
            earned.append(
                {
                    "badge_id": "consistent-performer",
                    "name": "Consistent Performer",
                    "level": "advanced",
                    "reason": (
                        f"Average interview score {avg_i:.2f} across "
                        f"{len(interview_scores)} sessions"
                    ),
                }
            )
    else:
        next_badges.append(
            {
                "badge_id": "solid-interview",
                "name": "Solid Interview",
                "level": "intermediate",
                "reason": "Complete an interview with score ≥ 0.60",
            }
        )

    # Always recognize profile activity; never return empty earned
    if not earned:
        earned.append(
            {
                "badge_id": "getting-started",
                "name": "Getting Started",
                "level": "beginner",
                "reason": (
                    f"Candidate {payload.candidate_id} is active — "
                    "complete a track, assessment, or interview to unlock more"
                ),
            }
        )

    # Deduplicate next vs earned by badge_id
    earned_ids = {b["badge_id"] for b in earned}
    next_badges = [b for b in next_badges if b["badge_id"] not in earned_ids]
    if not next_badges:
        next_badges.append(
            {
                "badge_id": "skill-specialist",
                "name": "Skill Specialist",
                "level": "advanced",
                "reason": "Demonstrate depth in a target skill across interviews",
            }
        )

    return {"earned": earned[:6], "next_badges": next_badges[:6]}


def _parse_badges(items: Any) -> list[BadgeItem]:
    out: list[BadgeItem] = []
    if not isinstance(items, list):
        return out
    seen: set[str] = set()
    for i, b in enumerate(items):
        if not isinstance(b, dict):
            continue
        badge_id = str(b.get("badge_id") or b.get("id") or f"badge-{i}").strip()
        name = str(b.get("name") or b.get("title") or "Badge").strip()
        if not badge_id or not name or badge_id in seen:
            continue
        seen.add(badge_id)
        out.append(
            BadgeItem(
                badge_id=badge_id,
                name=name,
                level=(str(b["level"]).strip() if b.get("level") is not None else None),
                reason=(
                    str(b["reason"]).strip() if b.get("reason") is not None else None
                ),
            )
        )
    return out


class BadgesService:
    async def recommend(self, payload: BadgeRecommendRequest) -> BadgeRecommendResponse:
        local = _local_recommendations(payload)
        system = (
            "Recommend achievement badges from candidate performance evidence. "
            "Always return non-empty arrays. "
            "earned = badges justified by the supplied tracks/assessments/interviews. "
            "next_badges = concrete upcoming goals. "
            "If evidence is thin, still return a Getting Started earned badge and "
            "at least one next_badge. "
            "Return JSON only: "
            '{"earned":[{"badge_id","name","level","reason"}],'
            '"next_badges":[{"badge_id","name","level","reason"}]}'
        )
        user = (
            f"Candidate: {payload.candidate_id}\n"
            f"Tracks: {payload.track_results}\n"
            f"Assessments: {payload.assessment_results}\n"
            f"Interviews: {payload.interview_scores}\n"
            f"Local baseline (use if unsure): {local}"
        )

        data, stub, provider = await generate_json(
            system=system,
            user=user,
            local_factory=lambda: local,
        )
        if not isinstance(data, dict):
            data = local
            stub = True
            provider = f"{provider}+invalid_payload"

        earned = _parse_badges(data.get("earned"))
        next_badges = _parse_badges(data.get("next_badges"))

        # Never return empty — merge local baseline when LLM omits badges
        if not earned or not next_badges:
            baseline = _local_recommendations(payload)
            if not earned:
                earned = _parse_badges(baseline["earned"])
                stub = True
                provider = f"{provider}+local_earned"
            if not next_badges:
                next_badges = _parse_badges(baseline["next_badges"])
                stub = True
                provider = f"{provider}+local_next"
            # Keep next distinct from earned
            earned_ids = {b.badge_id for b in earned}
            next_badges = [b for b in next_badges if b.badge_id not in earned_ids]
            if not next_badges:
                next_badges = _parse_badges(baseline["next_badges"])

        return BadgeRecommendResponse(
            correlation_id=payload.correlation_id,
            candidate_id=payload.candidate_id,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Badge recommendations via {provider}",
            earned=earned[:8],
            next_badges=next_badges[:8],
        )
