"""
jurisdiction.py - Stage 0: project intake and jurisdiction / code profile (LLM).

Turns whatever project metadata we have (intake form fields and/or values
derived from the cover sheet) into a code profile that tells Stage 7 which
review paths apply (IBC, ADA, TAS/TDLR, etc.). Returns {} on failure so the
rest of the pipeline degrades gracefully.
"""

import json
from typing import Dict, Optional

from backend import config
from backend.pipeline._stage import call_stage
from backend.prompts import JURISDICTION_SYSTEM_PROMPT, JURISDICTION_USER_INSTRUCTION


def run_jurisdiction(project_input: Optional[Dict]) -> Dict:
    """Build the project code profile from available project metadata."""
    project_input = project_input or {}
    parsed = call_stage(
        JURISDICTION_SYSTEM_PROMPT,
        JURISDICTION_USER_INSTRUCTION,
        subs={"project_input": json.dumps(project_input, ensure_ascii=True)},
        max_tokens=config.JURISDICTION_MAX_TOKENS,
    )
    if not isinstance(parsed, dict):
        print("[Jurisdiction] no profile produced; code review will be limited")
        return {}
    # The prompt wraps the result in "project_code_profile"; unwrap when present.
    profile = parsed.get("project_code_profile")
    return profile if isinstance(profile, dict) else parsed


def active_review_paths(profile: Dict) -> Dict:
    """The review_paths sub-dict (which code checks are on), or {} if absent."""
    return (profile or {}).get("review_paths") or {}
