"""
KnowledgeGraphClient — local cache of best fixes from platform KG.

Synced via PatternCache. Provides instant (<1ms) lookups for DiagnosisRouter.
No network calls in the hot path — all data is pre-cached.
"""

import logging
from dataclasses import dataclass
from typing import Any

logger = logging.getLogger("aigie.judge.kg_client")


@dataclass
class KGMatch:
    """A fix match from the Knowledge Graph."""

    strategy: str
    fix_content: str
    success_rate: float
    occurrence_count: int
    confidence: float
    workflow_match: bool = False
    framework_match: bool = False

    @property
    def is_high_confidence(self) -> bool:
        """True if this match is reliable enough to use directly."""
        return self.confidence >= 0.6 and self.success_rate >= 0.7


class KnowledgeGraphClient:
    """Local KG cache. Synced from platform by PatternCache."""

    MIN_SUCCESS_RATE = 0.3

    def __init__(self):
        self._cache: dict[str, dict[str, Any]] = {}

    def find_cached_fix(self, issue_domain: str, root_cause: str) -> KGMatch | None:
        """Find best fix from local cache. Returns None if no qualifying match."""
        key = f"{issue_domain}|{root_cause}"
        data = self._cache.get(key)
        if not data:
            return None
        if data.get("success_rate", 0) < self.MIN_SUCCESS_RATE:
            return None
        return KGMatch(
            strategy=data["strategy"],
            fix_content=data["fix_content"],
            success_rate=data["success_rate"],
            occurrence_count=data.get("occurrence_count", 0),
            confidence=data.get("confidence", 0.0),
            workflow_match=data.get("workflow_match", False),
            framework_match=data.get("framework_match", False),
        )

    def update_cache(self, fixes: dict[str, dict[str, Any]]) -> None:
        """Replace entire cache with new data from platform sync."""
        self._cache = fixes

    def cache_size(self) -> int:
        return len(self._cache)
