"""MCP tool registration for Report Parity & Progressive Validation Engine.

Provides 4 unified MCP tools (12 actions):
- report_parity: 4 actions (compile_spec, run, status, certificate)
- parity_test: 3 actions (execute, classify, fix)
- parity_report: 3 actions (analyze, suggest, compare)
- parity_manage: 2 actions (list_runs, reset_gate)
"""
from __future__ import annotations

import logging
from typing import Any, Dict, Optional

from .unified import (
    dispatch_report_parity,
    dispatch_parity_test,
    dispatch_parity_report,
    dispatch_parity_manage,
)

logger = logging.getLogger(__name__)


def register_report_parity_tools(mcp, settings):
    """Register the 4 unified report parity MCP tools."""

    @mcp.tool()
    def report_parity(
        action: str,
        report_json: Optional[str] = None,
        expected_values_json: Optional[str] = None,
        spec_json: Optional[str] = None,
        actual_values_json: Optional[str] = None,
        state_id: Optional[str] = None,
        state_json: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Report parity progressive validation.

        Actions:
        - compile_spec: Parse existing report into structured ReportSpec (requires report_json)
        - run: Execute progressive validation state machine (requires spec_json)
        - status: Get current gate status and progress (requires state_id)
        - certificate: Generate parity certificate (requires state_id or state_json)
        """
        return dispatch_report_parity(settings, action, **{
            k: v for k, v in {
                "report_json": report_json,
                "expected_values_json": expected_values_json,
                "spec_json": spec_json,
                "actual_values_json": actual_values_json,
                "state_id": state_id,
                "state_json": state_json,
            }.items() if v is not None
        })

    @mcp.tool()
    def parity_test(
        action: str,
        spec_json: Optional[str] = None,
        line_item_id: Optional[str] = None,
        period: Optional[str] = None,
        period_value: Optional[str] = None,
        actual_value: Optional[float] = None,
        result_json: Optional[str] = None,
        discrepancy_json: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Individual parity test operations.

        Actions:
        - execute: Run a single parity test (requires spec_json)
        - classify: Classify a discrepancy by root cause (requires result_json)
        - fix: Invoke FixGenerator for a discrepancy (requires discrepancy_json, spec_json)
        """
        return dispatch_parity_test(settings, action, **{
            k: v for k, v in {
                "spec_json": spec_json,
                "line_item_id": line_item_id,
                "period": period,
                "period_value": period_value,
                "actual_value": actual_value,
                "result_json": result_json,
                "discrepancy_json": discrepancy_json,
            }.items() if v is not None
        })

    @mcp.tool()
    def parity_report(
        action: str,
        spec_json: Optional[str] = None,
        actual_values_json: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Report analysis and improvement suggestions.

        Actions:
        - analyze: Analyze existing report for improvement opportunities (requires spec_json)
        - suggest: Generate improvement suggestions (requires spec_json)
        - compare: Side-by-side compare report values vs DW values (requires spec_json)
        """
        return dispatch_parity_report(settings, action, **{
            k: v for k, v in {
                "spec_json": spec_json,
                "actual_values_json": actual_values_json,
            }.items() if v is not None
        })

    @mcp.tool()
    def parity_manage(
        action: str,
        state_id: Optional[str] = None,
        gate_index: Optional[int] = None,
    ) -> Dict[str, Any]:
        """Manage validation runs.

        Actions:
        - list_runs: List past validation runs
        - reset_gate: Reset a failed gate for re-testing (requires state_id, gate_index)
        """
        return dispatch_parity_manage(settings, action, **{
            k: v for k, v in {
                "state_id": state_id,
                "gate_index": gate_index,
            }.items() if v is not None
        })

    logger.info("Registered 4 unified report parity tools: report_parity, parity_test, parity_report, parity_manage")
    return {
        "tools_registered": 4,
        "unified_tools": ["report_parity", "parity_test", "parity_report", "parity_manage"],
    }
