"""
Kodara Engine Client — calls the private backend API.

The core ranking and analysis algorithms run on Kodara's private servers.
Only the local index metadata is sent (no source code, no secrets).
"""

from __future__ import annotations

import os

BACKEND_URL = os.getenv("KODARA_API_URL", "https://web-production-6ee84.up.railway.app")
_TIMEOUT = 30.0


def _post(path: str, payload: dict) -> dict:
    try:
        import httpx
    except ImportError:
        raise RuntimeError(
            "httpx is required. Install with: pip install httpx"
        )

    url = f"{BACKEND_URL}{path}"
    try:
        r = httpx.post(url, json=payload, timeout=_TIMEOUT)
        r.raise_for_status()
        return r.json()
    except httpx.ConnectError:
        raise RuntimeError(
            f"Cannot reach Kodara engine at {BACKEND_URL}.\n"
            "Check your internet connection or set KODARA_API_URL."
        )
    except httpx.TimeoutException:
        raise RuntimeError("Engine request timed out. Try again.")
    except httpx.HTTPStatusError as e:
        detail = ""
        try:
            detail = e.response.json().get("detail", "")
        except Exception:
            pass
        raise RuntimeError(detail or str(e))


def query_context(
    modules: dict,
    graph_edges: list,
    query: str,
    max_modules: int = 8,
    depth: int = 1,
) -> dict:
    """
    Run the context selection engine against the local index.

    Sends: query + serialized index metadata (no source code)
    Returns: dict with modules, summaries, relevant_files, graph_fragment, token_estimate
    """
    return _post("/v1/context/query", {
        "query": query,
        "modules": modules,
        "graph_edges": graph_edges,
        "max_modules": max_modules,
        "depth": depth,
    })


def query_impact(
    modules: dict,
    target_path: str,
) -> dict:
    """
    Run the impact analyzer against the local index.

    Sends: module metadata + target path
    Returns: dict with direct, indirect, risk_level, critical_paths, etc.
    """
    return _post("/v1/impact/analyze", {
        "modules": modules,
        "target_path": target_path,
    })
