"""Tier configuration loading and capability resolution."""

import json
import re
from pathlib import Path
from typing import Optional


def load_tier_config(config_path: Optional[str] = None) -> dict:
    """Load tier_definitions.json from the given path or project default."""
    if config_path is None:
        config_path = Path(__file__).parent.parent.parent / "config" / "tier_definitions.json"
    else:
        config_path = Path(config_path)

    if not config_path.exists():
        raise FileNotFoundError(f"Tier config not found: {config_path}")

    with open(config_path, "r", encoding="utf-8") as f:
        return json.load(f)


def resolve_capabilities(tier_name: str, config: dict) -> set:
    """Recursively resolve all capabilities for a tier by following the includes chain."""
    tiers = config.get("tiers", {})
    tier = tiers.get(tier_name)
    if tier is None:
        raise ValueError(f"Unknown tier: {tier_name}")

    capabilities = set(tier.get("capabilities", []))

    parent = tier.get("includes")
    if parent and parent in tiers:
        capabilities |= resolve_capabilities(parent, config)

    return capabilities


def parse_agent_frontmatter(md_path: str) -> dict:
    """Split YAML frontmatter from markdown content in an agent definition file.

    Returns dict with keys:
        - 'frontmatter': dict of parsed YAML key-values
        - 'body': str of markdown content after frontmatter
    """
    md_path = Path(md_path)
    if not md_path.exists():
        raise FileNotFoundError(f"Agent definition not found: {md_path}")

    text = md_path.read_text(encoding="utf-8")

    # Match YAML frontmatter between --- delimiters
    match = re.match(r"^---\s*\n(.*?)\n---\s*\n(.*)", text, re.DOTALL)
    if not match:
        return {"frontmatter": {}, "body": text}

    yaml_text = match.group(1)
    body = match.group(2)

    # Simple YAML parser — handles flat keys and lists without pulling in PyYAML
    frontmatter = {}
    current_key = None
    current_list = None

    for line in yaml_text.split("\n"):
        stripped = line.strip()
        if not stripped or stripped.startswith("#"):
            continue

        # List item under a key
        if stripped.startswith("- ") and current_key is not None:
            if current_list is None:
                current_list = []
            current_list.append(stripped[2:].strip().strip('"').strip("'"))
            frontmatter[current_key] = current_list
            continue

        # Key: value pair
        if ":" in stripped:
            # Flush previous list
            current_list = None

            key, _, value = stripped.partition(":")
            key = key.strip()
            value = value.strip().strip('"').strip("'")
            current_key = key

            if value == "":
                # Might be followed by a list
                frontmatter[key] = []
                current_list = frontmatter[key]
            elif value.startswith("[") and value.endswith("]"):
                # Inline list: [Read, Grep, Glob]
                items = [item.strip().strip('"').strip("'") for item in value[1:-1].split(",")]
                frontmatter[key] = [i for i in items if i]
                current_list = None
            else:
                frontmatter[key] = value
                current_list = None

    return {"frontmatter": frontmatter, "body": body}
