"""Loads SDK signature YAML files from sdk_signatures/ directory."""
import os
from pathlib import Path
from typing import Dict, List, Optional
try:
    import yaml
except ImportError:
    yaml = None


def _parse_yaml_simple(text: str) -> dict:
    """Minimal YAML parser for simple flat/nested structures (fallback if PyYAML not available)."""
    import re
    result = {}
    stack = [result]
    indent_stack = [-1]
    current_list_key = None

    for raw_line in text.splitlines():
        if not raw_line.strip() or raw_line.strip().startswith("#"):
            continue
        indent = len(raw_line) - len(raw_line.lstrip())
        line = raw_line.strip()

        while len(indent_stack) > 1 and indent <= indent_stack[-1]:
            indent_stack.pop()
            stack.pop()

        if line.startswith("- "):
            val = line[2:].strip().strip('"').strip("'")
            parent = stack[-1]
            if isinstance(parent, list):
                parent.append(val)
            elif isinstance(parent, dict) and current_list_key:
                if current_list_key not in parent:
                    parent[current_list_key] = []
                parent[current_list_key].append(val)
        elif ":" in line:
            key, _, val = line.partition(":")
            key = key.strip()
            val = val.strip().strip('"').strip("'")
            parent = stack[-1]
            if isinstance(parent, dict):
                current_list_key = key
                if val == "" or val is None:
                    parent[key] = {}
                    stack.append(parent[key])
                    indent_stack.append(indent)
                else:
                    parent[key] = val
    return result


class SignatureLoader:
    def __init__(self, sig_dir: Path):
        self.sig_dir = sig_dir
        self.db_version = "unknown"

    def load(self, categories: Optional[List[str]] = None) -> List[dict]:
        meta_path = self.sig_dir / "_meta.yaml"
        if meta_path.exists():
            try:
                text = meta_path.read_text(encoding="utf-8")
                meta = yaml.safe_load(text) if yaml else _parse_yaml_simple(text)
                self.db_version = meta.get("version", "unknown")
            except Exception:
                pass

        signatures = []
        for cat_dir in sorted(self.sig_dir.iterdir()):
            if not cat_dir.is_dir() or cat_dir.name.startswith("_"):
                continue
            if categories and cat_dir.name not in categories:
                continue
            for yaml_file in sorted(cat_dir.glob("*.yaml")):
                try:
                    text = yaml_file.read_text(encoding="utf-8")
                    sig = yaml.safe_load(text) if yaml else _parse_yaml_simple(text)
                    if sig and "id" in sig:
                        signatures.append(sig)
                except Exception as e:
                    print(f"[WARN] Failed to load {yaml_file}: {e}")
        return signatures
