#!/usr/bin/env python3
"""
Minimal script to validate that all arguments in a YAML config file
are properly included in the tool signature.
"""

import argparse
import re
import sys
from pathlib import Path
from typing import Dict, List, Set

import yaml


def extract_signature_params(signature: str) -> Set[str]:
    """Extract parameter names from a tool signature string."""
    # Match required params: <param_name>
    required_pattern = r'<(\w+)>'
    # Match optional params: [<param_name>] or [<--param-name>]
    optional_pattern = r'\[<([^>]+)>\]'
    
    required_params = set(re.findall(required_pattern, signature))
    optional_params = set(re.findall(optional_pattern, signature))
    
    # Clean up optional params that might have -- prefix
    cleaned_optional = set()
    for param in optional_params:
        if param.startswith('--'):
            cleaned_optional.add(param[2:].replace('-', '_'))
        else:
            cleaned_optional.add(param)
    
    return required_params | cleaned_optional


def extract_defined_arguments(arguments: List[Dict]) -> Set[str]:
    """Extract argument names from the arguments definition."""
    return {arg['name'] for arg in arguments}


def validate_config(config_path: Path) -> bool:
    """Validate that all defined arguments are in the signature."""
    try:
        with open(config_path) as f:
            config = yaml.safe_load(f)
        
        # Get the first (and likely only) tool
        tool_name = next(iter(config['tools']))
        tool_config = config['tools'][tool_name]
        
        signature = tool_config['signature']
        arguments = tool_config['arguments']
        
        signature_params = extract_signature_params(signature)
        defined_args = extract_defined_arguments(arguments)
        
        missing_from_signature = defined_args - signature_params
        extra_in_signature = signature_params - defined_args
        
        print(f"Validating {config_path}")
        print(f"Tool: {tool_name}")
        print(f"Signature: {signature}")
        print(f"Defined arguments: {sorted(defined_args)}")
        print(f"Signature parameters: {sorted(signature_params)}")
        
        if missing_from_signature:
            print(f"❌ MISSING from signature: {sorted(missing_from_signature)}")
            return False
        
        if extra_in_signature:
            print(f"⚠️  EXTRA in signature: {sorted(extra_in_signature)}")
        
        if not missing_from_signature and not extra_in_signature:
            print("✅ All arguments properly included in signature")
            return True
        
        return not missing_from_signature
        
    except Exception as e:
        print(f"Error validating {config_path}: {e}")
        return False


def main():
    parser = argparse.ArgumentParser(description="Validate YAML config signatures")
    parser.add_argument("config_files", nargs="+", help="YAML config files to validate")
    args = parser.parse_args()
    
    all_valid = True
    for config_file in args.config_files:
        config_path = Path(config_file)
        if not config_path.exists():
            print(f"❌ File not found: {config_path}")
            all_valid = False
            continue
            
        valid = validate_config(config_path)
        all_valid = all_valid and valid
        print()
    
    sys.exit(0 if all_valid else 1)


if __name__ == "__main__":
    main()
