import os
import json
from src.config import UTILS_DIR, SCRIPT_CONFIG

class ConfigUtils:
    @staticmethod
    def generate_global_config():
        """Scan directory structure and generate global configuration file"""
        try:
            config = {"plugins": []}
            
            # Ensure utils directory exists
            if not os.path.exists(UTILS_DIR):
                os.makedirs(UTILS_DIR, exist_ok=True)
                print(f"Created UTILS_DIR: {UTILS_DIR}")
            
            # List items in utils directory for debugging
            print(f"UTILS_DIR contents: {os.listdir(UTILS_DIR) if os.path.exists(UTILS_DIR) else 'Directory does not exist'}")
            
            # Scan mode directories (first level subdirectories)
            mode_dirs = [d for d in os.listdir(UTILS_DIR) 
                        if os.path.isdir(os.path.join(UTILS_DIR, d)) and not d.startswith('_')]
            
            print(f"Found mode directories: {mode_dirs}")
            
            for mode_name in mode_dirs:
                mode_path = os.path.join(UTILS_DIR, mode_name)
                
                mode_info = {
                    "mode": mode_name,
                    "display_name": mode_name.replace("_", " ").title(),
                    "models": []
                }
                
                # List items in mode directory for debugging
                print(f"Contents of mode {mode_name}: {os.listdir(mode_path)}")
                
                # Scan model directories (second level subdirectories)
                model_dirs = [d for d in os.listdir(mode_path) 
                            if os.path.isdir(os.path.join(mode_path, d)) and not d.startswith('_')]
                
                print(f"Found models in mode {mode_name}: {model_dirs}")
                
                for model_name in model_dirs:
                    model_path = os.path.join(mode_path, model_name)
                    
                    # Check for model configuration file
                    model_config_path = os.path.join(model_path, "config.json")
                    if os.path.exists(model_config_path):
                        try:
                            with open(model_config_path, "r", encoding="utf-8") as f:
                                model_config = json.load(f)
                            
                            print(f"Successfully read model config: {model_config_path}")
                            
                            model_summary = {
                                "name": model_name,
                                "display_name": model_config.get("display_name", model_name.replace("_", " ").title()),
                                "description": model_config.get("description", ""),
                                "compatible_devices": model_config.get("compatible_devices", [])
                            }
                            
                            mode_info["models"].append(model_summary)
                        except Exception as e:
                            print(f"Error reading model config {model_config_path}: {e}")
                    else:
                        print(f"Model config file not found: {model_config_path}")
                        # Optionally create template config file here
                
                # Only add modes with models
                if mode_info["models"]:
                    config["plugins"].append(mode_info)
            
            # Write the configuration file
            os.makedirs(os.path.dirname(SCRIPT_CONFIG), exist_ok=True)
            with open(SCRIPT_CONFIG, "w", encoding="utf-8") as f:
                json.dump(config, f, indent=2, ensure_ascii=False)
            
            print(f"Global configuration generated: {SCRIPT_CONFIG}")
            return config
        except Exception as e:
            print(f"Error generating global configuration: {e}")
            import traceback
            traceback.print_exc()
            return {"plugins": []}
    
    @staticmethod
    def create_model_config_template(model_path):
        """Create a template configuration file for a model"""
        try:
            model_name = os.path.basename(model_path)
            mode_name = os.path.basename(os.path.dirname(model_path))
            
            template_config = {
                "display_name": model_name.replace("_", " ").title(),
                "description": f"AI model for {model_name.replace('_', ' ')}",
                "model_file": f"{model_name}.nef",
                "input_info": {
                    "type": "video",  # Default to video
                    "supported_formats": ["mp4", "avi"]
                },
                "input_parameters": {
                    "threshold": 0.5
                },
                "compatible_devices": ["KL520", "KL720"]
            }
            
            config_path = os.path.join(model_path, "config.json")
            with open(config_path, "w", encoding="utf-8") as f:
                json.dump(template_config, f, indent=2, ensure_ascii=False)
                
            print(f"Created template config for {model_name}")
            return True
        except Exception as e:
            print(f"Error creating model config template: {e}")
            return False