#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Cross-domain knowledge transfer detection — Item 162.

  - Item 162: Cross-domain knowledge transfer detection (Learning)

When a pattern from domain A is successfully applied in domain B,
record the transfer for future routing.
"""
import logging
from datetime import datetime, timezone
from typing import Dict, Any, List, Optional

log = logging.getLogger("pulse.brain.cross_domain_transfer")

# In-memory transfer registry: {(source_domain, target_domain): {count, successes}}
_TRANSFER_REGISTRY: Dict[str, Dict[str, Any]] = {}
_MAX_REGISTRY = 500


def record_transfer(
    source_domain: str,
    target_domain: str,
    item_id: str,
    success: bool,
) -> None:
    """Record a cross-domain transfer event.

    Args:
        source_domain: domain where the pattern/item was learned.
        target_domain: domain where the pattern was applied.
        item_id: brain item ID being transferred.
        success: whether the task using this transferred knowledge succeeded.
    Fails open silently.
    """
    try:
        if not source_domain or not target_domain:
            return
        if source_domain == target_domain:
            return  # Not a transfer
        key = f"{source_domain.lower()}→{target_domain.lower()}"
        entry = _TRANSFER_REGISTRY.setdefault(key, {
            "source_domain": source_domain,
            "target_domain": target_domain,
            "transfer_count": 0,
            "success_count": 0,
            "item_ids": [],
        })
        entry["transfer_count"] += 1
        if success:
            entry["success_count"] += 1
        if item_id and item_id not in entry["item_ids"]:
            entry["item_ids"].append(item_id)
            entry["item_ids"] = entry["item_ids"][-10:]  # keep last 10
        # Trim if oversized
        if len(_TRANSFER_REGISTRY) > _MAX_REGISTRY:
            oldest = sorted(_TRANSFER_REGISTRY, key=lambda k: _TRANSFER_REGISTRY[k]["transfer_count"])
            del _TRANSFER_REGISTRY[oldest[0]]
    except Exception as exc:
        log.debug("record_transfer failed: %s", exc)


def get_transfer_routes() -> List[Dict[str, Any]]:
    """Return cross-domain transfer routes sorted by success rate.

    Returns list of:
        {source_domain, target_domain, transfer_count, success_rate}
    sorted by success_rate descending.
    Fails open (returns []) on any error.
    """
    try:
        routes = []
        for entry in _TRANSFER_REGISTRY.values():
            count = entry.get("transfer_count", 0)
            if count < 1:
                continue
            routes.append({
                "source_domain": entry["source_domain"],
                "target_domain": entry["target_domain"],
                "transfer_count": count,
                "success_count": entry.get("success_count", 0),
                "success_rate": round(entry.get("success_count", 0) / count, 3),
            })
        routes.sort(key=lambda x: x["success_rate"], reverse=True)
        return routes
    except Exception as exc:
        log.debug("get_transfer_routes failed: %s", exc)
        return []


def get_best_transfer_target(source_domain: str) -> Optional[str]:
    """Return the domain to which source_domain transfers most successfully.

    Returns target domain string or None if no transfers recorded.
    """
    try:
        candidates = [
            r for r in get_transfer_routes()
            if r["source_domain"].lower() == source_domain.lower()
            and r["transfer_count"] >= 2
        ]
        if candidates:
            return candidates[0]["target_domain"]
    except Exception:
        pass
    return None
