"""Module 6: task-specific scoring for structured outputs (used by scripts/evaluate.py)."""
from __future__ import annotations

import json
import re


def parse_json_object(text: str) -> dict | None:
    m = re.search(r"\{.*\}", text, re.S)
    if not m:
        return None
    try:
        obj = json.loads(m.group(0))
    except json.JSONDecodeError:
        return None
    return obj if isinstance(obj, dict) else None


def field_scores(output: str, expected: str, exact_fields: tuple[str, ...]) -> dict:
    """valid_json: parsed at all; keys: has every expected key; exact: share of exact_fields that match."""
    got = parse_json_object(output)
    want = json.loads(expected)
    if got is None:
        return {"valid_json": 0.0, "keys": 0.0, "exact": 0.0}
    keys = float(set(want) <= set(got))
    matches = [str(got.get(f, "")).strip().lower() == str(want.get(f, "")).strip().lower() for f in exact_fields]
    return {"valid_json": 1.0, "keys": keys, "exact": sum(matches) / len(matches) if matches else 1.0}


def aggregate(rows: list[dict]) -> dict:
    if not rows:
        return {}
    return {k: round(sum(r[k] for r in rows) / len(rows), 3) for k in rows[0]}
