import os
import json
from .utils import print_info, print_success, CYAN, RESET, GRAY

def load_knowledge_base():
    """Loads the AI keyword-to-plugin mappings from the JSON file."""
    try:
        # __file__ gives the path to the current python script (ai.py)
        # We then find the directory it's in and look for the JSON file there.
        current_dir = os.path.dirname(os.path.abspath(__file__))
        json_path = os.path.join(current_dir, 'knowledge_base.json')
        with open(json_path, 'r') as f:
            return json.load(f)
    except Exception as e:
        print_error(f"Critical Error: Could not load AI knowledge base: {e}")
        return {}

def scan_codebase_for_permissions():
    """Scans the project files to intelligently recommend native permissions."""
    ai_knowledge_base = load_knowledge_base()
    
    print_info(f"{CYAN}🤖 AI Agent scanning codebase for native features...{RESET}")
    
    found_plugins = {}
    
    for root, dirs, files in os.walk('.'):
        dirs[:] = [d for d in dirs if d not in ['node_modules', '.git', 'android', 'ios', 'dist', 'build', '.next', '.nuxt', 'www']]
        
        for file in files:
            if file.endswith(('.js', '.ts', '.jsx', '.tsx', '.vue', '.svelte', '.html')):
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                        content = f.read()
                        
                        for keyword, data in ai_knowledge_base.items():
                            if keyword in content and data["plugin"] not in found_plugins:
                                found_plugins[data["plugin"]] = data
                except Exception:
                    pass
                    
    return found_plugins
