#!/usr/bin/env python3
"""
Real-time Correction Integration
Runs on each message to detect corrections and retrieve relevant past learnings.
"""

import json
import sys
from pathlib import Path
from datetime import datetime

# Import sibling modules
SKILL_DIR = Path(__file__).parent
sys.path.insert(0, str(SKILL_DIR))

from capture import detect_correction, process_message, AUTHORITY_MAP
from retrieve import retrieve_corrections, format_as_memory, load_correction

CORRECTIONS_DIR = Path("/home/aria/.openclaw/workspace/agency/corrections")
SIGNAL_LOG = CORRECTIONS_DIR / "realtime_signals.jsonl"


def process_incoming_message(
    message: str,
    sender_username: str,
    my_previous_response: str = "",
    channel: str = "discord"
) -> dict:
    """
    Full pipeline for processing an incoming message:
    1. Check if it's a correction → capture draft if so
    2. Extract intent → retrieve relevant past corrections
    3. Return actionable context
    
    Returns:
        {
            "correction_detected": bool,
            "correction_draft": dict | None,
            "relevant_corrections": list,
            "inject_context": str  # Pre-formatted text to inject
        }
    """
    result = {
        "correction_detected": False,
        "correction_draft": None,
        "relevant_corrections": [],
        "inject_context": "",
    }
    
    # Step 1: Check if this message IS a correction
    is_correction, detection_type, confidence = detect_correction(message)
    
    if is_correction and confidence >= 0.7:
        result["correction_detected"] = True
        
        # Create draft
        capture_result = process_message(
            message=message,
            sender_username=sender_username,
            my_previous_response=my_previous_response,
            channel=channel
        )
        
        if capture_result.get("draft"):
            result["correction_draft"] = capture_result["draft"]
            
            # Log the signal
            log_entry = {
                "timestamp": datetime.now().isoformat(),
                "type": "correction_received",
                "from": sender_username,
                "confidence": confidence,
                "detection_type": detection_type,
                "draft_id": capture_result["draft"]["id"],
            }
            
            CORRECTIONS_DIR.mkdir(exist_ok=True)
            with open(SIGNAL_LOG, 'a') as f:
                f.write(json.dumps(log_entry) + "\n")
    
    # Step 2: Retrieve relevant corrections for this message context
    # (regardless of whether it's a correction itself)
    corrections = retrieve_corrections(message, top_n=3)
    result["relevant_corrections"] = [c[1] for c in corrections]  # Extract just the correction dict
    
    # Step 3: Format inject context
    if corrections:
        lines = ["💡 **Relevant past learnings:**"]
        for score, cor in corrections[:3]:
            formatted = format_as_memory(score, cor)
            lines.append(f"  • {formatted}")
        result["inject_context"] = "\n".join(lines)
    
    return result


def check_recent_messages(messages: list) -> dict:
    """
    Batch check a list of recent messages for correction patterns.
    Useful for heartbeat scans.
    
    Args:
        messages: List of {"content": str, "author": str, "id": str}
    
    Returns:
        Summary of detected corrections and signals
    """
    corrections_found = []
    
    for msg in messages:
        is_correction, detection_type, confidence = detect_correction(
            msg.get("content", "")
        )
        
        if is_correction and confidence >= 0.7:
            corrections_found.append({
                "message_id": msg.get("id"),
                "author": msg.get("author"),
                "type": detection_type,
                "confidence": confidence,
                "preview": msg.get("content", "")[:100],
            })
    
    return {
        "total_scanned": len(messages),
        "corrections_detected": len(corrections_found),
        "corrections": corrections_found,
    }


def get_pre_response_context(message: str) -> str:
    """
    Quick lookup: Get any relevant corrections before responding.
    Returns formatted string to mentally consider, or empty string.
    """
    corrections = retrieve_corrections(message, top_n=2)
    
    if not corrections:
        return ""
    
    lines = []
    for score, cor in corrections:
        title = cor.get('title') or cor.get('what_was_wrong', 'No title')[:50]
        lines.append(f"⚠️ Remember: {title} ({cor['id']})")
    
    return "\n".join(lines)


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: integrate.py <username> <message> [previous_response]")
        print("\nExample:")
        print('  integrate.py "jim" "no, you should deploy to prod via Cloud Run"')
        sys.exit(1)
    
    username = sys.argv[1]
    message = sys.argv[2]
    previous = sys.argv[3] if len(sys.argv) > 3 else ""
    
    result = process_incoming_message(message, username, previous)
    print(json.dumps(result, indent=2, default=str))
