import json
from pathlib import Path
from typing import Dict, Any, Optional

class GHLSynergyBridge:
    """
    Bridges GHL Knowledge Graph data with BrowserController.
    Prevents redundant scraping and enables 'Informed Navigation'.
    """
    def __init__(self, kg_path: str = "E:/genesis-system/KNOWLEDGE_GRAPH/entities/ghl"):
        self.kg_path = Path(kg_path)
        self.selector_cache: Dict[str, str] = {}
        self.endpoint_cache: Dict[str, Dict] = {}

    def load_ghl_context(self):
        """Loads all relevant GHL entities into memory."""
        # Load API endpoints
        api_file = self.kg_path / "ghl_api_endpoints.json"
        if api_file.exists():
            with open(api_file, 'r') as f:
                data = json.load(f)
                self.endpoint_cache = data.get("GHL_API", {}).get("endpoints", {})

        # Common GHL Selectors (Production - Informed Navigation)
        self.selector_cache = {
            "sidebar_settings": "#sidebar-v2 .settings-icon, i.fa-cog, .sidebar-settings-link",
            "agency_api_key_input": "input[name='apiKey']",
            "agency_api_key_copy": ".api-key-copy-button, button:has-text('Copy')",
            "subaccount_create_btn": "button:has-text('Create Sub-account'), .btn-create-subaccount",
            "subaccount_save_btn": "button:has-text('Save'), .btn-save",
            "search_locations": "input[placeholder='Search Locations']",
            "location_switch_btn": ".location-switcher, .switch-account-btn"
        }

        # Load workflow patterns
        workflow_file = self.kg_path / "workflow_patterns_library.json"
        if workflow_file.exists():
            with open(workflow_file, 'r') as f:
                self.workflows = json.load(f)

    def get_selector(self, component_name: str) -> Optional[str]:
        """Retrieves a CSS selector from the KB for a GHL component."""
        return self.selector_cache.get(component_name)

    def get_api_endpoint(self, action: str) -> Optional[str]:
        """Returns the V2 API endpoint for a specific GHL action."""
        # Recursive search in endpoint_cache
        for category, data in self.endpoint_cache.items():
            endpoints = data.get("key_endpoints", {})
            if action in endpoints:
                return endpoints[action].get("path")
        return None

if __name__ == "__main__":
    bridge = GHLSynergyBridge()
    bridge.load_ghl_context()
    print(f"Loaded {len(bridge.endpoint_cache)} GHL API endpoints.")
