#!/usr/bin/env python3
"""
review_component.py
Script to review and validate dialogue component configurations.
Loads from component_configs.yaml and checks against rules.
"""

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 validate_component(component_data):
    component_type = component_data.get('component_type')
    configs = load_configs()
    if component_type not in configs['components']:
        return {"status": "error", "issues": [f"Unknown component type: {component_type}"]}

    component_config = configs['components'][component_type]
    issues = []
    config_data = component_data.get('config', {})

    # Check required fields
    required_fields = component_config.get('required_fields', list(component_config['format'].keys()))
    for field in required_fields:
        if field not in config_data or not config_data[field]:
            issues.append(f"Missing or empty required field: {field}")

    # Check validation rules (simplified)
    for rule in component_config['validation_rules']:
        if "must not be empty" in rule:
            for field in component_config['format']:
                if field in config_data and not config_data[field]:
                    issues.append(f"Field {field} {rule}")

    status = "approved" if not issues else "needs_fix"
    return {"component_type": component_type, "issues": issues, "status": status}

def main():
    parser = argparse.ArgumentParser(description="Review dialogue component configuration.")
    parser.add_argument('--file', required=True, help="Component JSON file to review")
    parser.add_argument('--strict', action='store_true', help="Fail on any issues")

    args = parser.parse_args()

    try:
        with open(args.file, 'r', encoding='utf-8') as f:
            component_data = json.load(f)

        result = validate_component(component_data)
        print(json.dumps(result, indent=2, ensure_ascii=False))

        if args.strict and result['status'] != 'approved':
            sys.exit(1)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()