"""Bridge to FixGenerator + Closure Engine for automated discrepancy resolution."""
from __future__ import annotations

import logging
from typing import Any, Dict, List, Optional

from .contracts import Discrepancy, ReportSpec

logger = logging.getLogger(__name__)


class FixLoopBridge:
    """Bridge parity discrepancies to the autonomous fix loop.

    Converts Discrepancy objects to closure engine event format and
    invokes run_closure_loop() from src/codex_graphrag/closure_engine.py.
    """

    def convert_to_event(
        self,
        discrepancy: Discrepancy,
        spec: ReportSpec,
    ) -> Dict[str, Any]:
        """Convert a Discrepancy to a closure engine event dict."""
        return {
            "metric": discrepancy.test_result.line_item_id,
            "symptom": (
                f"{discrepancy.discrepancy_type.value}: "
                f"diff={discrepancy.test_result.difference_pct:.2%}"
            ),
            "source_system": spec.source_system,
            "report_name": spec.report_name,
            "expected_value": discrepancy.test_result.expected_value,
            "actual_value": discrepancy.test_result.actual_value,
            "discrepancy_type": discrepancy.discrepancy_type.value,
            "confidence": discrepancy.confidence,
            "root_cause": discrepancy.root_cause_detail,
            "suggested_fix": discrepancy.suggested_fix,
            "dw_query": discrepancy.test_result.dw_query,
            "lineage_path": [spec.source_system, spec.report_name, discrepancy.test_result.line_item_id],
        }

    def invoke_fix(
        self,
        discrepancy: Discrepancy,
        spec: ReportSpec,
    ) -> Dict[str, Any]:
        """Invoke the fix loop for a discrepancy.

        Attempts to use the closure engine; falls back to returning
        the fix suggestion if the engine is not available.
        """
        event = self.convert_to_event(discrepancy, spec)

        try:
            from src.codex_graphrag.closure_engine import run_closure_loop
            result = run_closure_loop(event)
            return {
                "status": "fix_attempted",
                "closure_result": result,
                "event": event,
            }
        except ImportError:
            logger.info("Closure engine not available, returning suggestion only")
            return {
                "status": "suggestion_only",
                "suggested_fix": discrepancy.suggested_fix,
                "event": event,
            }
        except Exception as e:
            logger.error("Fix loop failed: %s", e)
            return {
                "status": "fix_failed",
                "error": str(e),
                "event": event,
            }

    def invoke_batch(
        self,
        discrepancies: List[Discrepancy],
        spec: ReportSpec,
    ) -> List[Dict[str, Any]]:
        """Invoke fix loop for multiple discrepancies."""
        return [self.invoke_fix(d, spec) for d in discrepancies]
