"""Model Context Protocol (MCP) server for BehavLock.

Supports two execution modes:
1. Remote Streamable HTTP (mounted inside `app/main.py` at `/api/mcp`) so any
   external developer can connect Google Antigravity, Cursor, or any MCP client
   with zero repo cloning.
2. Local `stdio` transport (`python behavlock_mcp_server.py`) for local/offline
   developer workflows pointing at `BEHAVLOCK_URL` (defaults to the hosted
   BehavLock endpoint, overridable via environment variable).
"""

from __future__ import annotations

import asyncio
import json
import logging
import os
from pathlib import Path
import sys
from typing import Any, Dict, List, Optional

import httpx
from mcp.server.fastmcp import FastMCP

try:
    from mcp.server.transport_security import TransportSecuritySettings

    _TRANSPORT_SECURITY: Optional[TransportSecuritySettings] = TransportSecuritySettings(
        enable_dns_rebinding_protection=False
    )
except ImportError:
    _TRANSPORT_SECURITY = None

try:
    from dotenv import load_dotenv

    load_dotenv(Path(__file__).resolve().parent / ".env")
except ImportError:
    pass

# Strictly log to stderr so stdout remains clean for MCP JSON-RPC framing.
logging.basicConfig(
    stream=sys.stderr,
    level=logging.INFO,
    format="[behavlock-mcp] %(levelname)s: %(message)s",
)
logger = logging.getLogger("behavlock-mcp")

DEFAULT_BEHAVLOCK_URL = "https://behavlock-bg25.onrender.com"

# Enabled by app/main.py when mounted as a Streamable HTTP ASGI endpoint so
# tool calls run directly in-process without loopback HTTP overhead.
_IN_PROCESS_MODE = False


def enable_in_process_mode() -> None:
    """Switch MCP tools to call BehavLock backend modules directly in-process."""
    global _IN_PROCESS_MODE
    _IN_PROCESS_MODE = True


def get_behavlock_url() -> str:
    """Return configured BehavLock API base URL without trailing slash."""
    return (os.environ.get("BEHAVLOCK_URL") or DEFAULT_BEHAVLOCK_URL).strip().rstrip("/")


_fastmcp_kwargs: Dict[str, Any] = {
    "stateless_http": True,
    "streamable_http_path": "/mcp",
}
if _TRANSPORT_SECURITY is not None:
    _fastmcp_kwargs["transport_security"] = _TRANSPORT_SECURITY

mcp = FastMCP("BehavLock", **_fastmcp_kwargs)


def _read_python_file(file_path: str, label: str) -> str:
    """Read a UTF-8 Python source file from disk with clear validation errors."""
    path = Path(file_path).expanduser()
    if not path.exists():
        raise FileNotFoundError(f"{label} file not found: {file_path}")
    if not path.is_file():
        raise ValueError(f"{label} path is not a file: {file_path}")
    return path.read_text(encoding="utf-8")


def _resolve_python_source(code: str, file_path: str, label: str) -> str:
    """Prefer raw Python source code string; fall back to local file path if given."""
    if code and code.strip():
        return code
    if file_path and file_path.strip():
        return _read_python_file(file_path.strip(), label)
    param_prefix = label.lower()
    raise ValueError(
        f"Missing {label.lower()} source: pass raw Python code in `{param_prefix}_code` "
        f"(recommended for remote MCP) or provide `{param_prefix}_file_path` for local stdio."
    )


def _parse_sample_traces(sample_traces_json: str) -> List[Dict[str, Any]]:
    """Parse sample_traces_json string into a list of trace objects."""
    raw = (sample_traces_json or "").strip()
    if not raw:
        return []
    parsed = json.loads(raw)
    if not isinstance(parsed, list):
        raise ValueError("sample_traces_json must be a JSON array of trace objects.")
    return parsed


def _format_gate_result(
    report: Dict[str, Any],
    mining_source: str,
    mining_note: Optional[str] = None,
) -> Dict[str, Any]:
    """Normalize BehavLock gate report into a concise MCP tool response."""
    vol_info = report.get("normalized_volatile_fields") or {}
    regressions: List[Dict[str, Any]] = []
    for grp in report.get("root_cause_groups") or []:
        rep = grp.get("representative_case") or {}
        regressions.append(
            {
                "signature": grp.get("signature"),
                "title": grp.get("title"),
                "severity": grp.get("severity"),
                "violated_invariant_id": grp.get("violated_invariant_id"),
                "violated_rule": grp.get("violated_invariant_rule"),
                "affected_cases_count": grp.get("count"),
                "minimal_failing_input": rep.get("input"),
                "expected_legacy_output": rep.get("legacy_result"),
                "actual_migrated_output": rep.get("migrated_result"),
                "field_diffs": rep.get("field_diffs"),
            }
        )

    receipt = report.get("receipt") or {}
    hashes = receipt.get("hashes") or {}

    result: Dict[str, Any] = {
        "verdict": report.get("status"),
        "cases_tested": report.get("total_cases_tested"),
        "passed_cases": report.get("passed_cases_count"),
        "failed_cases": report.get("failed_cases_count"),
        "volatile_fields_ignored": vol_info.get("fields", []),
        "volatile_bijective_ok": vol_info.get("bijective_match", True),
        "mining_source": mining_source,
        "root_cause_regressions": regressions,
        "receipt_sha256": hashes.get("receipt_signature_sha256"),
    }
    if mining_note:
        result["mining_note"] = mining_note
    return result


def _run_verify_in_process(
    legacy_code: str,
    migrated_code: str,
    sample_traces: List[Dict[str, Any]],
) -> Dict[str, Any]:
    """Execute invariant mining + dual-sandbox equivalence gate directly in-process."""
    from app.diff_engine import evaluate_behavioral_equivalence
    from app.gemini_miner import (
        GeminiApiError,
        GeminiConfigError,
        build_offline_baseline_invariants,
        mine_invariants_with_gemini,
    )
    from app.sandbox_runner import run_dual_sandbox

    mined_invariants: Optional[List[Dict[str, Any]]] = None
    mined_volatile: Optional[List[str]] = None
    mined_inputs: Optional[List[Dict[str, Any]]] = None
    mining_source = "ast_offline_fallback"
    mining_note: Optional[str] = None

    try:
        mine_data = mine_invariants_with_gemini(
            legacy_code=legacy_code,
            sample_traces=sample_traces,
            migrated_code=migrated_code,
        )
        mined_invariants = mine_data.get("invariants")
        mined_volatile = mine_data.get("volatile_fields")
        mined_inputs = mine_data.get("adversarial_test_inputs")
        mining_source = mine_data.get("source", "gemini")
    except SyntaxError as exc:
        return {
            "verdict": "ERROR",
            "error": f"Legacy Python code has a syntax error on line {exc.lineno}: {exc.msg}",
        }
    except (GeminiConfigError, GeminiApiError) as exc:
        mining_note = f"Gemini mining skipped ({exc}); used AST boundary generator."
        logger.warning(mining_note)
    except Exception as exc:
        mining_note = f"Gemini mining unavailable ({exc}); used AST boundary generator."
        logger.warning(mining_note)

    if not mined_inputs:
        try:
            baseline = build_offline_baseline_invariants(
                legacy_code=legacy_code,
                sample_traces=sample_traces,
            )
        except SyntaxError as exc:
            return {
                "verdict": "ERROR",
                "error": f"Legacy Python code has a syntax error on line {exc.lineno}: {exc.msg}",
            }
        mined_invariants = mined_invariants or baseline["invariants"]
        if mined_volatile is None:
            mined_volatile = baseline["volatile_fields"]
        mined_inputs = baseline["adversarial_test_inputs"]

    cases_meta: List[Dict[str, Any]] = []
    raw_args_list: List[Dict[str, Any]] = []
    for item in mined_inputs or []:
        if isinstance(item, dict) and "args" in item and isinstance(item["args"], dict):
            cases_meta.append(item)
            raw_args_list.append(item["args"])
        elif isinstance(item, dict):
            cases_meta.append(
                {"args": item, "rationale": "Custom input", "target_invariant_id": "INV-CUSTOM"}
            )
            raw_args_list.append(item)

    if not raw_args_list:
        return {
            "verdict": "ERROR",
            "error": "No valid adversarial test inputs could be constructed.",
        }

    try:
        exec_res = run_dual_sandbox(
            legacy_code=legacy_code,
            migrated_code=migrated_code,
            cases=raw_args_list,
        )
    except Exception as exc:
        return {"verdict": "ERROR", "error": f"BehavLock sandbox error: {exc}"}

    report = evaluate_behavioral_equivalence(
        fixture_id="mcp_verify",
        legacy_code=legacy_code,
        migrated_code=migrated_code,
        cases_meta=cases_meta,
        legacy_results=exec_res["legacy_results"],
        migrated_results=exec_res["migrated_results"],
        invariants=mined_invariants or [],
        volatile_fields=mined_volatile if mined_volatile is not None else [],
    )
    return _format_gate_result(report, mining_source, mining_note)


def _run_extract_in_process(legacy_code: str) -> Dict[str, Any]:
    """Execute legacy invariant mining directly in-process with AST fallback."""
    from app.gemini_miner import (
        GeminiApiError,
        GeminiConfigError,
        build_offline_baseline_invariants,
        mine_invariants_with_gemini,
    )

    try:
        data = mine_invariants_with_gemini(
            legacy_code=legacy_code,
            sample_traces=[],
        )
        return {
            "status": "OK",
            "model": data.get("model"),
            "invariants": data.get("invariants", []),
            "volatile_fields": data.get("volatile_fields", []),
            "ast_metadata": data.get("ast_metadata", {}),
            "adversarial_case_count": data.get("total_adversarial_count", 0),
        }
    except SyntaxError as exc:
        return {
            "status": "ERROR",
            "error": f"Legacy Python code has a syntax error on line {exc.lineno}: {exc.msg}",
        }
    except (GeminiConfigError, GeminiApiError) as exc:
        logger.warning("Gemini extraction failed (%s); falling back to AST analyzer.", exc)
        baseline = build_offline_baseline_invariants(legacy_code, [])
        return {
            "status": "OK_AST_FALLBACK",
            "model": "ast_offline_baseline",
            "invariants": baseline.get("invariants", []),
            "volatile_fields": baseline.get("volatile_fields", []),
            "ast_metadata": baseline.get("ast_metadata", {}),
            "adversarial_case_count": len(baseline.get("adversarial_test_inputs", [])),
            "warning": f"Gemini unavailable ({exc})",
        }
    except Exception as exc:
        return {"status": "ERROR", "error": str(exc)}


@mcp.tool()
async def verify_code_migration(
    legacy_code: str = "",
    migrated_code: str = "",
    legacy_file_path: str = "",
    migrated_file_path: str = "",
    sample_traces_json: str = "[]",
) -> Dict[str, Any]:
    """Verify that a migrated Python implementation is 100% behaviorally equivalent to its legacy version.

    Use this tool immediately after rewriting or patching a legacy Python function
    (especially financial, tax, billing, or cut-off logic) to catch silent regressions
    that unit tests miss: sub-rupee float rounding drift, off-by-one slab boundaries
    (>= vs >), missing null/empty guards, and swallowed validation exceptions.

    IMPORTANT FOR AI AGENTS:
        Always pass the full raw Python source code strings directly in `legacy_code`
        and `migrated_code` when calling BehavLock over remote MCP (Streamable HTTP),
        because the remote server cannot read files on your local filesystem.
        Only use `legacy_file_path` / `migrated_file_path` when running BehavLock
        locally via stdio on the same machine.

    Args:
        legacy_code: Raw Python source code string of the legacy implementation (recommended).
        migrated_code: Raw Python source code string of the AI-migrated implementation (recommended).
        legacy_file_path: Optional local file path to the legacy Python file (local stdio only).
        migrated_file_path: Optional local file path to the migrated Python file (local stdio only).
        sample_traces_json: Optional JSON array string of sample traces
            (`[{"input": {...}, "expected_legacy_output": {...}}]`).

    Returns:
        Structured verdict (`GATE_PASSED` or `GATE_FAILED`), `cases_tested`,
        `volatile_fields_ignored`, collapsed `root_cause_regressions` with minimal
        failing inputs and legacy vs. migrated outputs, and `receipt_sha256`.
    """
    try:
        resolved_legacy = _resolve_python_source(legacy_code, legacy_file_path, "Legacy")
        resolved_migrated = _resolve_python_source(migrated_code, migrated_file_path, "Migrated")
        sample_traces = _parse_sample_traces(sample_traces_json)
    except Exception as exc:
        return {"verdict": "ERROR", "error": str(exc)}

    if _IN_PROCESS_MODE:
        return await asyncio.to_thread(
            _run_verify_in_process, resolved_legacy, resolved_migrated, sample_traces
        )

    base_url = get_behavlock_url()
    mined_invariants: Optional[List[Dict[str, Any]]] = None
    mined_volatile: Optional[List[str]] = None
    mined_inputs: Optional[List[Dict[str, Any]]] = None
    mining_source = "ast_offline_fallback"
    mining_note: Optional[str] = None

    async with httpx.AsyncClient(base_url=base_url, timeout=60.0) as client:
        # Step 1: Try Gemini + AST invariant mining (gracefully fall back if offline/limited)
        try:
            mine_resp = await client.post(
                "/api/mine-invariants",
                json={
                    "fixture_id": "mcp_verify",
                    "legacy_code": resolved_legacy,
                    "migrated_code": resolved_migrated,
                    "sample_traces": sample_traces,
                },
                timeout=45.0,
            )
            if mine_resp.status_code == 200:
                mine_data = mine_resp.json()
                mined_invariants = mine_data.get("invariants")
                mined_volatile = mine_data.get("volatile_fields")
                mined_inputs = mine_data.get("adversarial_test_inputs")
                mining_source = mine_data.get("source", "gemini")
            else:
                detail = mine_resp.json().get("detail", mine_resp.text)
                mining_note = f"Gemini mining skipped ({mine_resp.status_code}: {detail}); used AST boundary generator."
                logger.warning(mining_note)
        except Exception as exc:
            mining_note = f"Gemini mining unavailable ({exc}); used AST boundary generator."
            logger.warning(mining_note)

        # Step 2: Execute dual-sandbox equivalence gate
        gate_payload: Dict[str, Any] = {
            "fixture_id": "mcp_verify",
            "legacy_code": resolved_legacy,
            "migrated_code": resolved_migrated,
            "sample_traces": sample_traces,
        }
        if mined_invariants is not None:
            gate_payload["invariants"] = mined_invariants
        if mined_volatile is not None:
            gate_payload["volatile_fields"] = mined_volatile
        if mined_inputs is not None:
            gate_payload["adversarial_test_inputs"] = mined_inputs

        try:
            gate_resp = await client.post("/api/run-gate", json=gate_payload, timeout=60.0)
        except Exception as exc:
            return {
                "verdict": "ERROR",
                "error": f"Failed to reach BehavLock API at {base_url}: {exc}",
            }

        if gate_resp.status_code != 200:
            try:
                err_detail = gate_resp.json().get("detail", gate_resp.text)
            except Exception:
                err_detail = gate_resp.text
            return {
                "verdict": "ERROR",
                "status_code": gate_resp.status_code,
                "error": f"BehavLock gate error: {err_detail}",
            }

        report = gate_resp.json()

    return _format_gate_result(report, mining_source, mining_note)


@mcp.tool()
async def extract_legacy_invariants(
    legacy_code: str = "",
    legacy_file_path: str = "",
) -> Dict[str, Any]:
    """Extract hidden business rules, boundary thresholds, and volatile fields from legacy code.

    Use this tool BEFORE rewriting a legacy Python function so you know every slab
    inequality, rounding convention (e.g. ROUND_HALF_UP vs float), exception
    contract, and non-deterministic output field (UUIDs/timestamps) that must
    be preserved in the migrated implementation.

    IMPORTANT FOR AI AGENTS:
        Always pass the raw Python source code string directly in `legacy_code`
        when calling BehavLock over remote MCP (Streamable HTTP). Only pass
        `legacy_file_path` when running BehavLock locally via stdio on the same machine.

    Args:
        legacy_code: Raw Python source code string of the legacy function/module (recommended).
        legacy_file_path: Optional local file path to the legacy Python file (local stdio only).

    Returns:
        Structured dictionary containing `invariants`, `volatile_fields`,
        `ast_metadata`, and `adversarial_case_count`.
    """
    try:
        resolved_legacy = _resolve_python_source(legacy_code, legacy_file_path, "Legacy")
    except Exception as exc:
        return {"status": "ERROR", "error": str(exc)}

    if _IN_PROCESS_MODE:
        return await asyncio.to_thread(_run_extract_in_process, resolved_legacy)

    base_url = get_behavlock_url()

    async with httpx.AsyncClient(base_url=base_url, timeout=45.0) as client:
        try:
            resp = await client.post(
                "/api/mine-invariants",
                json={
                    "fixture_id": "mcp_extract",
                    "legacy_code": resolved_legacy,
                    "sample_traces": [],
                },
            )
        except Exception as exc:
            return {
                "status": "ERROR",
                "error": f"Failed to reach BehavLock API at {base_url}: {exc}",
            }

        if resp.status_code != 200:
            try:
                err_detail = resp.json().get("detail", resp.text)
            except Exception:
                err_detail = resp.text
            logger.warning(
                "Gemini extraction failed (%s: %s); attempting AST fallback.",
                resp.status_code,
                err_detail,
            )
            try:
                from app.gemini_miner import build_offline_baseline_invariants

                baseline = build_offline_baseline_invariants(resolved_legacy, [])
                return {
                    "status": "OK_AST_FALLBACK",
                    "model": "ast_offline_baseline",
                    "invariants": baseline.get("invariants", []),
                    "volatile_fields": baseline.get("volatile_fields", []),
                    "ast_metadata": baseline.get("ast_metadata", {}),
                    "adversarial_case_count": len(baseline.get("adversarial_test_inputs", [])),
                    "warning": f"Gemini unavailable ({resp.status_code}: {err_detail})",
                }
            except Exception:
                return {
                    "status": "ERROR",
                    "status_code": resp.status_code,
                    "error": err_detail,
                }

        data = resp.json()

    return {
        "status": "OK",
        "model": data.get("model"),
        "invariants": data.get("invariants", []),
        "volatile_fields": data.get("volatile_fields", []),
        "ast_metadata": data.get("ast_metadata", {}),
        "adversarial_case_count": data.get("total_adversarial_count", 0),
    }


if __name__ == "__main__":
    logger.info("Starting BehavLock MCP server (BEHAVLOCK_URL=%s)", get_behavlock_url())
    mcp.run(transport="stdio")
