#!/usr/bin/env python3
"""
RTExit Skill Customization Resolver
Merges skill's customize.toml with team/user overrides.
Usage: python3 resolve_customization.py --skill /path/to/skill --key agent
"""

import argparse
import json
import os
import sys


def parse_simple_toml(content: str) -> dict:
    """Simple TOML parser."""
    result = {}
    current_section = result
    current_section_path = []

    for line in content.splitlines():
        line = line.strip()
        if not line or line.startswith('#'):
            continue

        if line.startswith('[[') and line.endswith(']]'):
            # Array of tables
            section_path = line[2:-2].split('.')
            current_section_path = section_path
            current_obj = result
            for part in section_path[:-1]:
                if part not in current_obj:
                    current_obj[part] = {}
                current_obj = current_obj[part]
            last_key = section_path[-1]
            if last_key not in current_obj:
                current_obj[last_key] = []
            new_item = {}
            current_obj[last_key].append(new_item)
            current_section = new_item

        elif line.startswith('[') and line.endswith(']'):
            section_path = line[1:-1].split('.')
            current_section_path = section_path
            current_section = result
            for part in section_path:
                if part not in current_section:
                    current_section[part] = {}
                current_section = current_section[part]

        elif '=' in line:
            key, _, value = line.partition('=')
            key = key.strip()
            value = value.strip()
            if value.startswith('"') or value.startswith("'"):
                value = value.strip('"').strip("'")
            elif value.startswith('['):
                # Array: parse inline
                value = [v.strip().strip('"').strip("'")
                         for v in value.strip('[]').split(',') if v.strip()]
            elif value.lower() == 'true':
                value = True
            elif value.lower() == 'false':
                value = False
            current_section[key] = value

    return result


def load_toml(path: str) -> dict:
    if not os.path.exists(path):
        return {}
    with open(path, 'r', encoding='utf-8') as f:
        content = f.read()
    try:
        import tomllib
        with open(path, 'rb') as fb:
            return tomllib.load(fb)
    except ImportError:
        pass
    try:
        import tomli
        with open(path, 'rb') as fb:
            return tomli.load(fb)
    except ImportError:
        pass
    return parse_simple_toml(content)


def deep_merge(base: dict, override: dict) -> dict:
    result = dict(base)
    for key, value in override.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = deep_merge(result[key], value)
        elif key in result and isinstance(result[key], list) and isinstance(value, list):
            # Merge arrays of tables by 'code' key
            merged = list(result[key])
            for new_item in value:
                if isinstance(new_item, dict) and 'code' in new_item:
                    existing_idx = next(
                        (i for i, x in enumerate(merged)
                         if isinstance(x, dict) and x.get('code') == new_item['code']),
                        None
                    )
                    if existing_idx is not None:
                        merged[existing_idx] = deep_merge(merged[existing_idx], new_item)
                    else:
                        merged.append(new_item)
                else:
                    merged.append(new_item)
            result[key] = merged
        elif value not in ('', None, []):
            result[key] = value
    return result


def resolve_customization(skill_root: str, project_root: str = None) -> dict:
    """Load and merge customize.toml layers for a skill."""
    skill_name = os.path.basename(os.path.abspath(skill_root))

    layers = [os.path.join(skill_root, 'customize.toml')]

    if project_root:
        layers += [
            os.path.join(project_root, '_rtexit', 'custom', f'{skill_name}.toml'),
            os.path.join(project_root, '_rtexit', 'custom', f'{skill_name}.user.toml'),
        ]

    config = {}
    for layer in layers:
        layer_config = load_toml(layer)
        config = deep_merge(config, layer_config)

    return config


def main():
    parser = argparse.ArgumentParser(description='RTExit Customization Resolver')
    parser.add_argument('--skill', required=True, help='Skill root directory')
    parser.add_argument('--project-root', help='Project root (for custom overrides)')
    parser.add_argument('--key', help='Specific section to return (e.g. agent)')
    args = parser.parse_args()

    config = resolve_customization(args.skill, args.project_root)

    if args.key:
        result = config.get(args.key, {})
    else:
        result = config

    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    main()
