"""Contract loader and validator."""

from __future__ import annotations

import pathlib
import re


REQUIRED_SECTIONS = [
    "Goal",
    "Scope",
    "Out of scope",
    "Success Criteria",
    "Constraints",
    "Approvals required",
    "Notes",
]


def load_contract(path: str | pathlib.Path) -> str:
    p = pathlib.Path(path)
    if not p.exists():
        raise FileNotFoundError(f"Contract file not found: {p}")
    return p.read_text(encoding="utf-8")


def validate_contract(text: str) -> list[str]:
    """Return list of missing section names (empty == valid)."""
    missing: list[str] = []
    for section in REQUIRED_SECTIONS:
        pattern = re.compile(
            rf"^##\s+{re.escape(section)}\s*$", re.IGNORECASE | re.MULTILINE
        )
        if not pattern.search(text):
            missing.append(section)
    return missing


def load_and_validate(path: str | pathlib.Path) -> tuple[str, list[str]]:
    text = load_contract(path)
    missing = validate_contract(text)
    return text, missing


def parse_task_type(text: str) -> str:
    """Extract task type from contract. Defaults to 'map-gen' if absent."""
    match = re.search(
        r"^##\s+Task\s+Type\s*\n+\s*(\S+)",
        text,
        re.IGNORECASE | re.MULTILINE,
    )
    if match:
        return match.group(1).strip()
    return "map-gen"


def parse_scaffold_config(text: str) -> dict[str, str] | None:
    """Extract Scaffold section as key-value dict. Returns None if section missing."""
    match = re.search(
        r"^##\s+Scaffold\s*\n(.*?)(?=^##\s|\Z)",
        text,
        re.IGNORECASE | re.MULTILINE | re.DOTALL,
    )
    if not match:
        return None
    block = match.group(1).strip()
    result: dict[str, str] = {}
    for line in block.splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        colon = line.find(":")
        if colon == -1:
            continue
        key = line[:colon].strip().lower().replace(" ", "_")
        value = line[colon + 1 :].strip()
        if key:
            result[key] = value
    return result if result else None
