"""Lessons 3 and 4: deterministic metrics. Each returns a float in [0, 1]."""
from __future__ import annotations

import json
import re
import string
from collections import Counter

_ARTICLES = re.compile(r"\b(a|an|the)\b")


def normalize(text: str) -> str:
    """Lowercase, drop punctuation and articles, collapse whitespace (SQuAD-style)."""
    text = text.lower()
    text = "".join(ch for ch in text if ch not in set(string.punctuation))
    text = _ARTICLES.sub(" ", text)
    return " ".join(text.split())


def exact_match(output: str, expected: str) -> float:
    return float(normalize(output) == normalize(expected))


def token_f1(output: str, expected: str) -> float:
    out, ref = normalize(output).split(), normalize(expected).split()
    if not out or not ref:
        return float(out == ref)
    common = Counter(out) & Counter(ref)
    overlap = sum(common.values())
    if overlap == 0:
        return 0.0
    precision, recall = overlap / len(out), overlap / len(ref)
    return 2 * precision * recall / (precision + recall)


def contains_all(output: str, required: list[str]) -> float:
    """Fraction of required phrases present (case-insensitive). 1.0 means all present."""
    if not required:
        return 1.0
    low = output.lower()
    return sum(r.lower() in low for r in required) / len(required)


def contains_none(output: str, forbidden: list[str]) -> float:
    low = output.lower()
    return float(not any(f.lower() in low for f in forbidden))


def regex_match(output: str, pattern: str) -> float:
    return float(re.search(pattern, output) is not None)


def levenshtein(a: str, b: str) -> int:
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, start=1):
        cur = [i]
        for j, cb in enumerate(b, start=1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[-1]


def edit_similarity(output: str, expected: str) -> float:
    a, b = normalize(output), normalize(expected)
    if not a and not b:
        return 1.0
    return 1.0 - levenshtein(a, b) / max(len(a), len(b))


def extract_json(text: str):
    """Parse the first JSON object or array in text, tolerating ```json fences and prose around it."""
    fenced = re.search(r"```(?:json)?\s*(.*?)```", text, re.S)
    if fenced:
        text = fenced.group(1)
    decoder = json.JSONDecoder()
    for i, ch in enumerate(text):
        if ch in "{[":
            try:
                obj, _ = decoder.raw_decode(text[i:])
                return obj
            except json.JSONDecodeError:
                continue
    raise ValueError("no JSON found")


_TYPES = {"string": str, "number": (int, float), "integer": int, "boolean": bool, "array": list, "object": dict}


def json_schema_score(output: str, schema: dict) -> float:
    """1.0 if output contains JSON with all required keys of the right basic types; partial credit per key.

    `schema` is a tiny subset of JSON Schema: {"required": [...], "properties": {"k": {"type": "string"}}}.
    """
    try:
        obj = extract_json(output)
    except ValueError:
        return 0.0
    if not isinstance(obj, dict):
        return 0.0
    required = schema.get("required", [])
    if not required:
        return 1.0
    props = schema.get("properties", {})
    ok = 0
    for key in required:
        if key not in obj:
            continue
        want = props.get(key, {}).get("type")
        value = obj[key]
        if want is None or (isinstance(value, _TYPES[want]) and not (want in ("number", "integer") and isinstance(value, bool))):
            ok += 1
    return ok / len(required)


REFUSAL_PATTERNS = [r"\bI can(?:'|no)t help\b", r"\bI(?:'m| am) (?:not able|unable) to\b", r"\bI won'?t\b",
                    r"\bI do not have (?:access|information)\b", r"\bI don'?t know\b", r"\bas an AI\b"]


def is_refusal(output: str) -> float:
    return float(any(re.search(p, output, re.I) for p in REFUSAL_PATTERNS))


def length_within(output: str, min_words: int = 0, max_words: int = 10**9) -> float:
    n = len(output.split())
    return float(min_words <= n <= max_words)
