#!/usr/bin/env python3
"""
RTExit Configuration Resolver
Merges 4 config layers (base → user → team → personal) into final config.
Usage: python3 resolve_config.py --project-root /path [--key section]
"""

import argparse
import json
import os
import sys

try:
    import tomllib
except ImportError:
    try:
        import tomli as tomllib
    except ImportError:
        # Fallback: simple TOML parser for basic key=value
        tomllib = None


def parse_simple_toml(content: str) -> dict:
    """Simple TOML parser for basic key=value pairs (no dependencies)."""
    result = {}
    current_section = result

    for line in content.splitlines():
        line = line.strip()
        if not line or line.startswith('#'):
            continue
        if line.startswith('[') and line.endswith(']'):
            section_path = line[1:-1].split('.')
            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().strip('"').strip("'")
            if 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, 'rb') as f:
        content = f.read()
    if tomllib:
        return tomllib.loads(content.decode('utf-8'))
    return parse_simple_toml(content.decode('utf-8'))


def deep_merge(base: dict, override: dict) -> dict:
    """Deep merge two dicts. Override values win."""
    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):
            result[key] = result[key] + value
        elif value != '' and value is not None:
            result[key] = value
    return result


def resolve_config(project_root: str) -> dict:
    """Merge 4 config layers."""
    layers = [
        os.path.join(project_root, '_rtexit', 'config.toml'),
        os.path.join(project_root, '_rtexit', 'config.user.toml'),
        os.path.join(project_root, '_rtexit', 'custom', 'config.toml'),
        os.path.join(project_root, '_rtexit', 'custom', 'config.user.toml'),
    ]

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

    # Resolve path templates
    config = resolve_templates(config, project_root)
    return config


def resolve_templates(obj, project_root: str):
    """Replace {project-root} and other templates in string values."""
    if isinstance(obj, dict):
        return {k: resolve_templates(v, project_root) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [resolve_templates(i, project_root) for i in obj]
    elif isinstance(obj, str):
        dir_name = os.path.basename(os.path.abspath(project_root))
        return obj.replace('{project-root}', project_root).replace('{dir-name}', dir_name)
    return obj


def main():
    parser = argparse.ArgumentParser(description='RTExit Config Resolver')
    parser.add_argument('--project-root', required=True, help='Project root directory')
    parser.add_argument('--key', help='Specific config section to return')
    args = parser.parse_args()

    config = resolve_config(args.project_root)

    if args.key:
        # Navigate nested keys like "agents.commander"
        parts = args.key.split('.')
        result = config
        for part in parts:
            result = result.get(part, {})
    else:
        result = config

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


if __name__ == '__main__':
    main()
