#!/usr/bin/env python3
"""
generate_component.py
Script to generate standardized configurations for dialogue components.
Loads from component_configs.yaml and produces JSON output.
"""

import argparse
import json
import yaml
import sys
import os

CONFIG_FILE = os.path.join(os.path.dirname(__file__), '..', 'component_configs.yaml')

def load_configs():
    with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
        return yaml.safe_load(f)

def generate_component(component_type, **kwargs):
    configs = load_configs()
    if component_type not in configs['components']:
        raise ValueError(f"Unknown component type: {component_type}")

    component_config = configs['components'][component_type]
    # Merge provided kwargs with defaults
    config = {**component_config['config'], **kwargs}

    output = {
        "component_type": component_type,
        "format": component_config['format'],
        "config": config,
        "status": "generated"
    }
    return output

def main():
    parser = argparse.ArgumentParser(description="Generate dialogue component configuration.")
    parser.add_argument('--type', required=True, help="Component type (e.g., dialogue_reading)")
    parser.add_argument('--output', default='component.json', help="Output file")
    # Add dynamic args based on config, but for simplicity, use kwargs
    args, unknown = parser.parse_known_args()

    # Parse additional kwargs
    kwargs = {}
    for arg in unknown:
        if '=' in arg:
            key, value = arg.split('=', 1)
            kwargs[key] = value

    try:
        result = generate_component(args.type, **kwargs)
        with open(args.output, 'w', encoding='utf-8') as f:
            json.dump(result, f, indent=2, ensure_ascii=False)
        print(f"Generated component config saved to {args.output}")
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()