"""
Semantic intent router for Marziel.

Uses semantic-router + fastembed for instant (~5ms) intent classification.
Falls back to keyword matching if semantic-router is not installed.
"""

import logging
from typing import Optional

logger = logging.getLogger("marziel.router")

# ── Route definitions ──
# Each route has: name, utterances (training examples), and associated action
ROUTE_DEFINITIONS = {
    "web_search": [
        "search for latest news",
        "google this topic",
        "find information about",
        "look up on the internet",
        "what are the latest updates on",
        "search the web for",
        "find me articles about",
        "current news about",
        "what happened today with",
        "latest developments in",
        "search for latest AI news",
        "search the web for quantum computing",
        "look this up online",
        "find recent news about",
        "search online for",
        "web search for",
        "can you search for",
        "google search for",
        "find out about",
    ],
    "agent": [
        "run a command on my system",
        "check my disk space",
        "list files in this directory",
        "execute this bash script",
        "show me system processes",
        "check my RAM usage",
        "install this package",
        "run ls -la",
        "what ports are open",
        "show system uptime",
        "run this terminal command",
        "check CPU usage",
        "open file and read contents",
        "write to a file",
        "delete this file",
        "find files matching pattern",
    ],
    "browser": [
        "open this website",
        "navigate to google.com",
        "take a screenshot of the page",
        "click on the login button",
        "fill out this form",
        "browse this URL",
        "go to this webpage",
        "open a browser and visit",
        "show me what this website looks like",
        "scroll down on the page",
    ],
    "maritime": [
        "what are current bunker prices",
        "show vessel tracking data",
        "maritime weather forecast",
        "port congestion report",
        "AIS vessel positions",
        "shipping route analysis",
        "piracy risk zones",
        "Baltic Dry Index today",
        "freight rates for tankers",
        "GDACS disaster alerts for shipping",
        "IMO regulations update",
        "cargo vessel status",
        "ocean current conditions",
        "maritime risk assessment",
        "voyage fuel consumption analysis",
    ],
    "code": [
        "write a python function",
        "debug this code",
        "create a sorting algorithm",
        "fix this JavaScript error",
        "write a REST API endpoint",
        "explain this code snippet",
        "optimize this function",
        "write unit tests for",
        "convert this to TypeScript",
        "create a class that handles",
    ],
    "github": [
        "analyze this GitHub repository",
        "check stars on this repo",
        "what languages does this project use",
        "show me the README of",
        "who are the contributors to",
        "analyze the architecture of this repo",
        "github.com/",
        "how many forks does this have",
        "what issues are open on",
        "review this repository",
    ],
    "url": [
        "read this article",
        "summarize this webpage",
        "what does this link say",
        "extract content from this URL",
        "analyze this page",
        "read the content at this link",
        "what is on this website",
        "parse this URL for me",
    ],
    "chat": [
        "hello how are you",
        "tell me about artificial intelligence",
        "what is the meaning of life",
        "explain quantum computing",
        "write me a poem",
        "tell me a joke",
        "who are you",
        "what can you do",
        "help me understand",
        "let's discuss philosophy",
        "what do you think about",
        "can you explain",
        "I need advice on",
        "have a conversation with me",
    ],
}

# ── Tier gating per route ──
ROUTE_TIER_REQUIREMENTS = {
    "chat": "free",
    "web_search": "free",
    "url": "free",
    "code": "pro",
    "github": "pro",
    "browser": "pro",
    "agent": "pro",
    "maritime": "enterprise",
}

TIER_HIERARCHY = {"free": 0, "pro": 1, "enterprise": 2}

# ── Semantic router (lazy loaded) ──
_router_instance = None
_router_available = None


def _init_semantic_router():
    """Initialize the semantic router with fastembed embeddings (lazy, one-time)."""
    global _router_instance, _router_available

    if _router_available is not None:
        return _router_available

    try:
        from semantic_router import Route, SemanticRouter
        from semantic_router.encoders import FastEmbedEncoder

        encoder = FastEmbedEncoder(model_name="BAAI/bge-small-en-v1.5")

        routes = []
        for route_name, utterances in ROUTE_DEFINITIONS.items():
            routes.append(Route(name=route_name, utterances=utterances))

        _router_instance = SemanticRouter(encoder=encoder, routes=routes)
        # Sync the index — embeds all utterances and builds the local vector index
        _router_instance.sync("local")
        _router_available = True
        logger.info("🧭 Semantic router initialized (fastembed BGE-small)")
        return True

    except ImportError:
        logger.info("🧭 semantic-router not installed, using keyword fallback")
        _router_available = False
        return False
    except Exception as e:
        logger.warning(f"🧭 Semantic router init failed: {e}, using keyword fallback")
        _router_available = False
        return False


# ── Keyword fallback (existing logic) ──
_AGENT_KEYWORDS = {
    "run", "execute", "command", "terminal", "bash", "shell", "script",
    "read file", "write file", "create file", "open file", "save file",
    "delete file", "show file", "cat ", "view file",
    "disk", "storage", "memory", "ram", "cpu", "process", "port",
    "check system", "check my", "system info", "device info",
    "os version", "uptime", "hostname", "ip address",
    "run code", "execute code", "run python", "run script",
    "use bash", "use terminal", "check file", "list files", "ls ",
    "df ", "du ", "top ", "ps ", "grep ", "find ",
    "install", "pip ", "npm ", "brew ",
    "browse", "open page", "navigate to", "go to website",
    "visit ", "open url", "screenshot", "click on",
    "fill form", "open browser",
}

_SEARCH_KEYWORDS = {
    "search", "google", "look up", "find out", "latest news",
    "current", "today", "what happened", "recent",
}

_MARITIME_KEYWORDS = {
    "maritime", "vessel", "ship", "voyage", "port", "ais", "imo",
    "bunker", "ballast", "cargo", "freight", "shipping route",
    "piracy", "cyclone", "storm", "sea weather", "ocean",
}

_GITHUB_KEYWORDS = {"github", "repo", "repository", "stars", "fork", "commit"}

_BROWSER_KEYWORDS = {"browse", "open page", "navigate to", "go to website",
                     "visit ", "open url", "screenshot", "click on", "open browser"}

_CODE_KEYWORDS = {"code", "python", "javascript", "function", "class", "debug",
                  "compile", "algorithm", "programming", "execute", "sandbox"}


def _keyword_route(message: str) -> str:
    """Fallback keyword-based routing."""
    lower = message.lower().strip()

    # Check most specific first
    if any(k in lower for k in _GITHUB_KEYWORDS):
        return "github"
    if any(k in lower for k in _BROWSER_KEYWORDS):
        return "browser"
    if any(k in lower for k in _MARITIME_KEYWORDS):
        return "maritime"
    if any(k in lower for k in _AGENT_KEYWORDS):
        return "agent"
    if any(k in lower for k in _CODE_KEYWORDS):
        return "code"
    if any(k in lower for k in _SEARCH_KEYWORDS):
        return "web_search"

    # Check for URL patterns
    if "http://" in lower or "https://" in lower or "www." in lower:
        if "github.com" in lower:
            return "github"
        return "url"

    return "chat"


def semantic_route(message: str) -> str:
    """
    Route a message to the most appropriate intent.

    Returns one of: chat, web_search, agent, browser, maritime, code, github, url
    """
    # Try semantic router first
    if _init_semantic_router() and _router_instance is not None:
        try:
            result = _router_instance(message)
            route_name = result.name if result and result.name else None
            if route_name:
                logger.debug(f"🧭 Semantic route: '{message[:50]}' → {route_name}")
                return route_name
        except Exception as e:
            logger.warning(f"Semantic routing failed: {e}")

    # Fallback to keywords
    route = _keyword_route(message)
    logger.debug(f"🧭 Keyword route: '{message[:50]}' → {route}")
    return route


def is_route_allowed(route: str, user_tier: str) -> bool:
    """Check if a route is allowed for the given tier."""
    required = ROUTE_TIER_REQUIREMENTS.get(route, "free")
    return TIER_HIERARCHY.get(user_tier, 0) >= TIER_HIERARCHY.get(required, 0)


def get_route_tier_requirement(route: str) -> str:
    """Get the minimum tier needed for a route."""
    return ROUTE_TIER_REQUIREMENTS.get(route, "free")
