"""Cross-device pattern discovery.

When patterns are confirmed on multiple nodes, their confidence
escalates automatically. This module provides the logic for
multi-node pattern convergence.
"""
from __future__ import annotations

from greymatter_core.sync.tracking import get_node_id

# Confidence escalation: how many unique nodes confirming → confidence level
NODE_CONFIDENCE_MAP = {
    1: "low",
    2: "medium",
    3: "high",
    4: "verified",  # 4+ nodes → verified
}


def escalate_pattern_confidence(db, pattern_id: str) -> str | None:
    """Check if a pattern has been confirmed across multiple nodes.

    Looks at _sync_log for upsert entries from different node_ids.
    If the pattern has been modified from multiple nodes, escalate
    its confidence level.

    Returns the new confidence level, or None if no change.
    """
    # Count unique nodes that have modified this pattern
    rows = db.execute(
        "SELECT DISTINCT node_id FROM _sync_log "
        "WHERE table_name = 'patterns' AND row_id = ? AND operation = 'upsert'",
        (pattern_id,),
    )
    unique_nodes = len(rows)

    if unique_nodes < 2:
        return None

    # Determine new confidence based on node count
    for threshold in sorted(NODE_CONFIDENCE_MAP.keys(), reverse=True):
        if unique_nodes >= threshold:
            new_confidence = NODE_CONFIDENCE_MAP[threshold]
            break
    else:
        return None

    # Check current confidence
    pattern = db.execute_one(
        "SELECT confidence FROM patterns WHERE id = ?", (pattern_id,)
    )
    if not pattern:
        return None

    current = pattern["confidence"]
    confidence_order = {"low": 0, "medium": 1, "high": 2, "verified": 3}

    # Only escalate, never downgrade
    if confidence_order.get(new_confidence, 0) > confidence_order.get(current, 0):
        db.execute(
            "UPDATE patterns SET confidence = ? WHERE id = ?",
            (new_confidence, pattern_id),
        )
        return new_confidence

    return None


def discover_cross_node_patterns(db) -> list[dict]:
    """Find patterns that have been confirmed across multiple nodes.

    Returns list of patterns with their node count and confidence change.
    """
    # Find patterns with activity from multiple nodes
    rows = db.execute(
        "SELECT row_id, COUNT(DISTINCT node_id) as node_count "
        "FROM _sync_log "
        "WHERE table_name = 'patterns' AND operation = 'upsert' "
        "GROUP BY row_id "
        "HAVING COUNT(DISTINCT node_id) >= 2 "
        "ORDER BY node_count DESC"
    )

    results = []
    for row in rows:
        pattern = db.execute_one(
            "SELECT id, title, confidence, confirmations FROM patterns WHERE id = ?",
            (row["row_id"],),
        )
        if pattern:
            new_conf = escalate_pattern_confidence(db, row["row_id"])
            results.append({
                "id": pattern["id"],
                "title": pattern["title"],
                "current_confidence": new_conf or pattern["confidence"],
                "previous_confidence": pattern["confidence"] if new_conf else None,
                "node_count": row["node_count"],
                "confirmations": pattern["confirmations"],
                "escalated": new_conf is not None,
            })

    return results
