"""MCP server for QuickCall recommendations. Run via: quickcall mcp-recs"""

from __future__ import annotations

import json
import os
from pathlib import Path

from fastmcp import FastMCP, Context

from qc_trace.mcp.rules import (
    get_accepted_rules,
    get_pending_rules,
    load_rules,
    resolve_repo_slug,
    send_feedback,
    update_rule_status,
)

QC_TRACE_DIR = Path(os.environ.get("QC_TRACE_CONFIG_DIR", str(Path.home() / ".quickcall-trace")))

mcp = FastMCP("quickcall-recs")


def _load_config() -> dict:
    """Load config.json for platform_url and platform_token."""
    config_path = QC_TRACE_DIR / "config.json"
    if config_path.exists():
        try:
            return json.loads(config_path.read_text())
        except (json.JSONDecodeError, OSError):
            pass
    return {}


@mcp.tool()
async def review_rules(ctx: Context) -> str:
    """Review pending QuickCall recommendations for this project.

    Presents each pending recommendation for accept/dismiss via interactive prompts.
    Accepted rules will be injected into future AI sessions automatically.
    """
    project_dir = os.environ.get("CLAUDE_PROJECT_DIR")
    if not project_dir:
        return "Could not determine project directory. CLAUDE_PROJECT_DIR not set."

    repo_slug = resolve_repo_slug(project_dir)
    if not repo_slug:
        return f"Could not determine repository for {project_dir}."

    rules_data = load_rules(QC_TRACE_DIR, repo_slug)
    if rules_data is None:
        return "No recommendations available for this repository."

    pending = get_pending_rules(rules_data)
    if not pending:
        accepted = get_accepted_rules(rules_data)
        return f"No pending recommendations. {len(accepted)} accepted rules active."

    config = _load_config()
    platform_url = config.get("platform_url", "https://api.quickcall.dev")
    platform_token = config.get("platform_token")

    results = []
    for rule in pending:
        result = await ctx.elicit(
            message=f"**{rule['rule']}**\n\nReason: {rule['reason']}\nConfidence: {rule['confidence']} ({rule['finding_count']} findings)",
            response_type=["accept", "dismiss"],
        )
        action = result.data if hasattr(result, "data") else str(result)

        if action == "accept":
            update_rule_status(QC_TRACE_DIR, repo_slug, rule["id"], "accepted")
            if platform_token:
                ok = send_feedback(platform_url, platform_token, rule["id"], "thumbs_up")
                if ok:
                    results.append(f"Accepted: {rule['rule'][:60]}...")
                else:
                    results.append(f"Accepted locally (server sync pending): {rule['rule'][:60]}...")
            else:
                results.append(f"Accepted locally: {rule['rule'][:60]}...")
        elif action == "dismiss":
            update_rule_status(QC_TRACE_DIR, repo_slug, rule["id"], "dismissed")
            if platform_token:
                ok = send_feedback(platform_url, platform_token, rule["id"], "thumbs_down")
                if ok:
                    results.append(f"Dismissed: {rule['rule'][:60]}...")
                else:
                    results.append(f"Dismissed locally (server sync pending): {rule['rule'][:60]}...")
            else:
                results.append(f"Dismissed locally: {rule['rule'][:60]}...")

    return f"Reviewed {len(results)} rules:\n" + "\n".join(results)


def run_mcp_server() -> None:
    """Entry point for quickcall mcp-recs subcommand."""
    mcp.run(transport="stdio")
