"""Shared assessment grading — MCQ auto-score, timing, skill reports.

Used by puzzles / aptitude / assessments / answers. Does not invent scores when
an answer key is provided — deterministic exact/normalized match first.
"""

from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import Any


def _norm(text: Any) -> str:
    s = str(text or "").strip().lower()
    s = re.sub(r"\s+", " ", s)
    return s


def _as_list(value: Any) -> list[str]:
    if value is None:
        return []
    if isinstance(value, list):
        return [str(v) for v in value if v is not None and str(v).strip()]
    if isinstance(value, str) and value.strip():
        return [value.strip()]
    return []


# Assessment `kind` labels — never treat these as competency skills.
_KIND_LABELS = frozenset(
    {
        "mcq",
        "coding",
        "case_study",
        "aptitude",
        "scenario",
        "essay",
        "video_response",
        "file_upload",
        "puzzle",
        "custom",
        "technical",
        "domain",
        "assessment",
        "answers",
    }
)


def is_kind_label(value: str | None) -> bool:
    if not value:
        return True
    return str(value).strip().lower().replace("-", "_") in _KIND_LABELS


def _clean_skills(values: list[str] | None) -> list[str]:
    """Drop empty / kind-label skills; keep real competency tags."""
    out: list[str] = []
    for raw in values or []:
        s = str(raw).strip()
        if not s or is_kind_label(s):
            continue
        if s not in out:
            out.append(s)
    return out


@dataclass
class GradedItem:
    question_id: str | None
    index: int
    score: float
    max_score: float
    is_correct: bool | None
    skill: str | None = None
    skills: list[str] = field(default_factory=list)
    feedback: str | None = None
    selected: str | None = None
    expected: str | None = None
    auto_scored: bool = False

    def as_dict(self) -> dict[str, Any]:
        return {
            "question_id": self.question_id,
            "index": self.index,
            "score": self.score,
            "max_score": self.max_score,
            "is_correct": self.is_correct,
            "skill": self.skill,
            "skills": list(self.skills or []),
            "feedback": self.feedback,
            "selected": self.selected,
            "expected": self.expected if self.auto_scored else None,
            "auto_scored": self.auto_scored,
        }


@dataclass
class SkillScore:
    skill: str
    score: float
    max_score: float
    items: int = 0
    correct: int = 0

    @property
    def ratio(self) -> float:
        return (self.score / self.max_score) if self.max_score else 0.0

    def as_dict(self) -> dict[str, Any]:
        return {
            "skill": self.skill,
            "score": round(self.score, 4),
            "max_score": round(self.max_score, 4),
            "ratio": round(self.ratio, 4),
            "items": self.items,
            "correct": self.correct,
        }


@dataclass
class TimingResult:
    time_limit_minutes: int | None
    time_taken_seconds: int | None
    timing_ok: bool | None
    overtime_seconds: int = 0
    penalty_applied: float = 0.0
    notes: list[str] = field(default_factory=list)

    def as_dict(self) -> dict[str, Any]:
        return {
            "time_limit_minutes": self.time_limit_minutes,
            "time_taken_seconds": self.time_taken_seconds,
            "timing_ok": self.timing_ok,
            "overtime_seconds": self.overtime_seconds,
            "penalty_applied": self.penalty_applied,
            "notes": self.notes,
        }


def extract_answer_value(answer: dict[str, Any]) -> str | None:
    for key in (
        "selected",
        "selected_key",
        "answer",
        "student_answer",
        "response",
        "value",
        "text",
    ):
        if key in answer and answer[key] is not None:
            return str(answer[key])
    return None


def extract_question_id(answer: dict[str, Any], index: int) -> str | None:
    for key in ("question_id", "id", "qid"):
        if answer.get(key):
            return str(answer[key])
    return f"q{index + 1}"


def _skills_from_question(q: Any) -> list[str]:
    if isinstance(q, dict):
        meta = q.get("metadata") or {}
        return _clean_skills(
            _as_list(meta.get("skills") or meta.get("skill") or q.get("skills") or q.get("skill"))
        )
    meta = getattr(q, "metadata", None) or {}
    return _clean_skills(_as_list(meta.get("skills") or meta.get("skill")))


def build_answer_key(questions: list[Any]) -> dict[str, dict[str, Any]]:
    """Map question_id → {answer, skills, max_score, stem, time_limit_minutes?}."""
    key: dict[str, dict[str, Any]] = {}
    for i, q in enumerate(questions or []):
        if isinstance(q, dict):
            qid = str(q.get("id") or q.get("question_id") or f"q{i + 1}")
            meta = q.get("metadata") or {}
            skills = _skills_from_question(q)
            answer = q.get("answer")
            # Also check options marked correct
            if not answer:
                for opt in q.get("options") or []:
                    if isinstance(opt, dict) and opt.get("is_correct"):
                        answer = opt.get("key") or opt.get("text")
                        break
            row: dict[str, Any] = {
                "answer": answer,
                "skills": skills,
                "max_score": float(q.get("max_score") or meta.get("max_score") or 1.0),
                "stem": q.get("stem") or q.get("text"),
            }
            tl = meta.get("time_limit_minutes") or q.get("time_limit_minutes")
            if tl is not None:
                row["time_limit_minutes"] = int(tl)
            key[qid] = row
        else:
            qid = str(getattr(q, "id", None) or f"q{i + 1}")
            meta = getattr(q, "metadata", None) or {}
            skills = _skills_from_question(q)
            answer = getattr(q, "answer", None)
            if not answer:
                for opt in getattr(q, "options", None) or []:
                    if getattr(opt, "is_correct", False):
                        answer = getattr(opt, "key", None) or getattr(opt, "text", None)
                        break
            row = {
                "answer": answer,
                "skills": skills,
                "max_score": float(meta.get("max_score") or 1.0),
                "stem": getattr(q, "stem", None),
            }
            tl = meta.get("time_limit_minutes")
            if tl is not None:
                row["time_limit_minutes"] = int(tl)
            key[qid] = row
    return key


def evaluate_timing(
    *,
    time_limit_minutes: int | None,
    time_taken_seconds: int | None,
    overtime_fail: bool = True,
    overtime_penalty_ratio: float = 0.0,
) -> TimingResult:
    if time_limit_minutes is None or time_taken_seconds is None:
        return TimingResult(
            time_limit_minutes=time_limit_minutes,
            time_taken_seconds=time_taken_seconds,
            timing_ok=None,
            notes=["Timing not fully provided — client-enforced timer assumed"],
        )
    limit_s = int(time_limit_minutes) * 60
    overtime = max(0, int(time_taken_seconds) - limit_s)
    ok = overtime == 0
    notes: list[str] = []
    penalty = 0.0
    if not ok:
        notes.append(f"Overtime by {overtime}s (limit {time_limit_minutes} min)")
        if overtime_penalty_ratio > 0:
            penalty = min(1.0, float(overtime_penalty_ratio))
            notes.append(f"Applied overtime penalty ratio={penalty:.2f}")
        if overtime_fail:
            notes.append("Marked timing_ok=false (overtime)")
    else:
        notes.append("Completed within time limit")
    return TimingResult(
        time_limit_minutes=time_limit_minutes,
        time_taken_seconds=time_taken_seconds,
        timing_ok=ok,
        overtime_seconds=overtime,
        penalty_applied=penalty,
        notes=notes,
    )


def auto_grade_answers(
    *,
    answers: list[dict[str, Any]],
    answer_key: dict[str, dict[str, Any]] | None,
    default_skill: str | None = None,
    assessment_skills: list[str] | None = None,
    passing_ratio: float = 0.6,
) -> tuple[list[GradedItem], float, float, list[SkillScore], bool]:
    """Deterministic grade when answer_key present; otherwise heuristic partial credit.

    Skills are derived from (in order): answer_key row, answer payload, round-robin
    ``assessment_skills``, then ``default_skill`` — never from assessment kind labels.
    """
    items: list[GradedItem] = []
    total = 0.0
    max_total = 0.0
    skill_map: dict[str, SkillScore] = {}
    pool = _clean_skills(list(assessment_skills or []))
    fallback = None if is_kind_label(default_skill) else (default_skill or None)

    for i, ans in enumerate(answers):
        if not isinstance(ans, dict):
            continue
        qid = extract_question_id(ans, i)
        selected = extract_answer_value(ans)
        key_row = (answer_key or {}).get(qid or "") if answer_key else None
        # Fallback: match by index order if ids missing in key
        if key_row is None and answer_key and len(answer_key) == len(answers):
            key_row = list(answer_key.values())[i]

        max_score = float(
            ans.get("max_score")
            or (key_row or {}).get("max_score")
            or 1.0
        )
        skills = _clean_skills(
            _as_list((key_row or {}).get("skills"))
            or _as_list(ans.get("skills") or ans.get("skill"))
        )
        if not skills and pool:
            skills = [pool[i % len(pool)]]
        if not skills and fallback:
            skills = [fallback]
        skill = skills[0] if skills else None

        expected = (key_row or {}).get("answer") if key_row else ans.get("expected_answer")
        auto = False
        is_correct: bool | None = None
        score = 0.0
        feedback = None

        if expected is not None and str(expected).strip() != "":
            auto = True
            is_correct = _norm(selected) == _norm(expected)
            # Also accept option text match when expected is a key letter
            if not is_correct and selected and expected:
                # loose containment for short answers
                if len(_norm(expected)) >= 3 and _norm(expected) in _norm(selected):
                    is_correct = True
            score = max_score if is_correct else 0.0
            feedback = "Correct." if is_correct else "Incorrect."
        else:
            # No key — heuristic: non-empty gets partial credit (legacy behavior)
            if selected and str(selected).strip():
                score = round(max_score * 0.7, 4)
                is_correct = None
                feedback = "Auto-scored without answer key (partial credit)."
            else:
                score = 0.0
                is_correct = False
                feedback = "Empty answer."

        total += score
        max_total += max_score
        items.append(
            GradedItem(
                question_id=qid,
                index=i,
                score=score,
                max_score=max_score,
                is_correct=is_correct,
                skill=skill,
                skills=list(skills),
                feedback=feedback,
                selected=selected,
                expected=str(expected) if expected is not None else None,
                auto_scored=auto,
            )
        )
        # Attribute this item to every tagged skill (not kind labels).
        for sk in skills:
            ss = skill_map.setdefault(
                sk, SkillScore(skill=sk, score=0.0, max_score=0.0)
            )
            ss.score += score
            ss.max_score += max_score
            ss.items += 1
            if is_correct:
                ss.correct += 1

    if max_total <= 0:
        max_total = float(len(items) or 1)
    passed = (total / max_total) >= passing_ratio if max_total else False
    return items, round(total, 4), round(max_total, 4), list(skill_map.values()), passed


def tag_questions_with_skills(
    questions: list[Any],
    skills: list[str],
    *,
    domain: str | None = None,
) -> list[Any]:
    """Stamp metadata.skills onto generated questions (round-robin if multiple)."""
    tags = _clean_skills(list(skills or []))
    if domain and not is_kind_label(domain) and domain not in tags:
        tags = tags or [domain]
    if not tags:
        return questions
    out = []
    for i, q in enumerate(questions):
        skill = tags[i % len(tags)]
        if hasattr(q, "model_copy"):
            meta = dict(getattr(q, "metadata", None) or {})
            meta.setdefault("skills", [skill])
            if domain:
                meta.setdefault("domain", domain)
            out.append(q.model_copy(update={"metadata": meta}))
        elif isinstance(q, dict):
            meta = dict(q.get("metadata") or {})
            meta.setdefault("skills", [skill])
            if domain:
                meta.setdefault("domain", domain)
            q = {**q, "metadata": meta}
            out.append(q)
        else:
            out.append(q)
    return out


def apply_timing_to_result(
    *,
    total: float,
    max_total: float,
    passed: bool,
    timing: TimingResult,
    fail_on_overtime: bool = True,
) -> tuple[float, bool, TimingResult]:
    if timing.penalty_applied > 0:
        total = round(total * (1.0 - timing.penalty_applied), 4)
    if fail_on_overtime and timing.timing_ok is False:
        passed = False
    elif max_total > 0:
        passed = total >= max_total * 0.6 if passed is None else passed
    return total, passed, timing


def normalize_answer_key(
    *,
    answer_key: dict[str, Any] | list[Any] | None = None,
    questions: list[Any] | None = None,
) -> dict[str, dict[str, Any]]:
    """Accept Platform-passed answer_key dict/list or full questions.

    Questions are applied first so flat answer_key maps (qid → \"A\") keep
    metadata.skills from the generated question bank.
    """
    key: dict[str, dict[str, Any]] = {}
    if questions:
        key.update(build_answer_key(questions))
    if isinstance(answer_key, dict):
        for qid, val in answer_key.items():
            if str(qid).startswith("_"):
                continue  # reserved meta keys
            if isinstance(val, dict) and (
                "answer" in val or "skills" in val or "skill" in val
            ):
                row = key.setdefault(str(qid), {})
                merged_skills = _clean_skills(
                    _as_list(val.get("skills") or val.get("skill"))
                    or _as_list(row.get("skills"))
                )
                row.update(
                    {
                        "answer": val.get("answer", row.get("answer")),
                        "skills": merged_skills,
                        "max_score": float(
                            val.get("max_score") or row.get("max_score") or 1.0
                        ),
                        "stem": val.get("stem", row.get("stem")),
                    }
                )
                if val.get("time_limit_minutes") is not None:
                    row["time_limit_minutes"] = int(val["time_limit_minutes"])
            else:
                row = key.setdefault(str(qid), {})
                row["answer"] = val
                row.setdefault("max_score", 1.0)
                # Preserve skills already loaded from questions
                row["skills"] = _clean_skills(_as_list(row.get("skills")))
    elif isinstance(answer_key, list):
        for i, item in enumerate(answer_key):
            if not isinstance(item, dict):
                continue
            qid = str(item.get("question_id") or item.get("id") or f"q{i + 1}")
            row = key.setdefault(qid, {})
            row["answer"] = item.get("answer") or item.get("expected")
            row["skills"] = _clean_skills(
                _as_list(item.get("skills") or item.get("skill") or row.get("skills"))
            )
            row["max_score"] = float(item.get("max_score") or row.get("max_score") or 1.0)
            row["stem"] = item.get("stem") or row.get("stem")
    return key


def export_answer_key(questions: list[Any]) -> dict[str, Any]:
    """Compact answer_key for generate responses (Platform persists)."""
    built = build_answer_key(questions)
    out: dict[str, Any] = {}
    for qid, row in built.items():
        out[qid] = {
            "answer": row.get("answer"),
            "skills": row.get("skills") or [],
            "max_score": row.get("max_score", 1.0),
        }
    return out


def resolve_time_limit(
    explicit: int | None,
    options: dict[str, Any] | None,
    rubric: dict[str, Any] | None = None,
    *,
    questions: list[Any] | None = None,
    answer_key: dict[str, dict[str, Any]] | None = None,
    default: int | None = None,
) -> int | None:
    """Resolve assessment time limit: explicit → options → rubric → questions → default."""
    if explicit is not None:
        return int(explicit)
    opts = options or {}
    if opts.get("time_limit_minutes") is not None:
        return int(opts["time_limit_minutes"])
    if rubric and rubric.get("time_limit_minutes") is not None:
        return int(rubric["time_limit_minutes"])
    for q in questions or []:
        if isinstance(q, dict):
            meta = q.get("metadata") or {}
            tl = meta.get("time_limit_minutes") or q.get("time_limit_minutes")
            if tl is not None:
                return int(tl)
        else:
            meta = getattr(q, "metadata", None) or {}
            if meta.get("time_limit_minutes") is not None:
                return int(meta["time_limit_minutes"])
    for row in (answer_key or {}).values():
        if isinstance(row, dict) and row.get("time_limit_minutes") is not None:
            return int(row["time_limit_minutes"])
    if default is not None:
        return int(default)
    return None


def resolve_time_taken(
    explicit: int | None,
    options: dict[str, Any] | None,
) -> int | None:
    if explicit is not None:
        return int(explicit)
    opts = options or {}
    if opts.get("time_taken_seconds") is not None:
        return int(opts["time_taken_seconds"])
    return None


def skill_score_dicts(scores: list[SkillScore]) -> list[dict[str, Any]]:
    return [s.as_dict() for s in scores]


def feedback_from_items(
    *,
    items: list[GradedItem],
    total: float,
    max_total: float,
    timing: TimingResult | None,
    label: str = "Assessment",
) -> str:
    correct = sum(1 for i in items if i.is_correct is True)
    n = len(items)
    lines = [
        f"### {label} results",
        f"- Score: **{total}** / {max_total}",
        f"- Correct: {correct}/{n}" if n else "- No items",
    ]
    if timing and timing.timing_ok is False:
        lines.append(
            f"- Timing: overtime by {timing.overtime_seconds}s "
            f"(limit {timing.time_limit_minutes} min)"
        )
    elif timing and timing.timing_ok is True:
        lines.append("- Timing: within limit")
    weak = [i for i in items if i.is_correct is False]
    if weak:
        focus: list[str] = []
        for item in weak:
            for sk in item.skills or ([item.skill] if item.skill else []):
                if sk and not is_kind_label(sk) and sk not in focus:
                    focus.append(sk)
        if focus:
            lines.append(f"- Focus areas: {', '.join(sorted(focus))}")
    return "\n".join(lines)
