#!/usr/bin/env python3
"""
Scan recent conversations for corrections.

Integrates with OpenClaw message flow:
1. Reads recent messages from memory files
2. Runs semantic classification on each
3. Creates draft corrections for high-confidence matches
4. Returns summary for heartbeat/cron processing
"""

import json
import os
import re
import sys
from datetime import datetime, timedelta
from pathlib import Path

# Add skill directory to path for imports
SKILL_DIR = Path(__file__).parent
sys.path.insert(0, str(SKILL_DIR))

from semantic_classifier import classify_message
from capture import process_message, AUTHORITY_MAP

MEMORY_DIR = Path("/home/aria/.openclaw/workspace/memory")
CORRECTIONS_LOG = Path("/home/aria/.openclaw/workspace/agency/Learnings/corrections.md")


def extract_conversations_from_memory(days_back: int = 1) -> list[dict]:
    """
    Extract conversation snippets from memory files.
    Returns list of {author, message, context, timestamp, source}
    """
    conversations = []
    today = datetime.now()
    
    for i in range(days_back + 1):
        date = today - timedelta(days=i)
        date_str = date.strftime("%Y-%m-%d")
        memory_file = MEMORY_DIR / f"{date_str}.md"
        
        if not memory_file.exists():
            continue
        
        content = memory_file.read_text()
        
        # Look for feedback/correction patterns in memory
        # Memory files contain summaries, not raw messages
        # Extract quoted feedback
        feedback_patterns = [
            r'"([^"]+)".*?(?:—|-).*?(\w+)',  # "quote" — Person
            r'###.*?Feedback.*?\n(.*?)(?=\n##|\Z)',  # ### Feedback sections
            r'\*\*(?:Correction|Feedback|Pushed back)\*\*:?\s*(.+)',  # **Correction**: text
        ]
        
        for pattern in feedback_patterns:
            matches = re.findall(pattern, content, re.DOTALL | re.IGNORECASE)
            for match in matches:
                if isinstance(match, tuple):
                    text, author = match[0].strip(), match[1].strip() if len(match) > 1 else "unknown"
                else:
                    text, author = match.strip(), "unknown"
                
                if len(text) > 10:  # Skip very short matches
                    conversations.append({
                        "author": author,
                        "message": text[:500],  # Limit length
                        "context": "",
                        "timestamp": date_str,
                        "source": str(memory_file)
                    })
    
    return conversations


def scan_for_corrections(
    conversations: list[dict] = None,
    days_back: int = 1,
    min_confidence: int = 70
) -> dict:
    """
    Scan conversations for corrections.
    
    Returns:
        {
            "scanned": int,
            "corrections_found": int,
            "flagged_for_review": int,
            "corrections": [...],
            "flagged": [...]
        }
    """
    if conversations is None:
        conversations = extract_conversations_from_memory(days_back)
    
    results = {
        "scanned": len(conversations),
        "corrections_found": 0,
        "flagged_for_review": 0,
        "corrections": [],
        "flagged": []
    }
    
    for conv in conversations:
        result = classify_message(
            message=conv["message"],
            context=conv.get("context", "")
        )
        
        if result.confidence >= min_confidence and result.is_correction:
            results["corrections_found"] += 1
            results["corrections"].append({
                "author": conv["author"],
                "message": conv["message"][:200],
                "confidence": result.confidence,
                "category": result.category,
                "reasoning": result.reasoning,
                "source": conv["source"],
                "timestamp": conv["timestamp"]
            })
        elif result.confidence >= 40:
            results["flagged_for_review"] += 1
            results["flagged"].append({
                "author": conv["author"],
                "message": conv["message"][:200],
                "confidence": result.confidence,
                "category": result.category,
                "reasoning": result.reasoning
            })
    
    return results


def process_incoming_message(
    message: str,
    author: str,
    context: str = "",
    channel: str = "discord",
    auto_log: bool = True
) -> dict:
    """
    Process a single incoming message for correction detection.
    
    This is the main hook for live message processing.
    Call this after receiving a user message.
    
    Returns classification result with draft path if logged.
    """
    result = process_message(
        message=message,
        sender_username=author,
        my_previous_response=context,
        channel=channel,
        use_semantic=True
    )
    
    return result


def get_recent_corrections_summary() -> str:
    """Get a summary of recently logged corrections."""
    if not CORRECTIONS_LOG.exists():
        return "No corrections logged yet."
    
    content = CORRECTIONS_LOG.read_text()
    
    # Count corrections
    corrections = content.count("### 20")
    
    # Get last few
    sections = content.split("### ")
    recent = sections[-3:] if len(sections) > 3 else sections[1:]
    
    summary = f"**{corrections} corrections logged**\n\nRecent:\n"
    for section in recent:
        if section.strip():
            # Extract first line (date | who | topic)
            first_line = section.split("\n")[0].strip()
            if first_line:
                summary += f"- {first_line}\n"
    
    return summary


def main():
    """CLI interface."""
    import argparse
    
    parser = argparse.ArgumentParser(description="Scan conversations for corrections")
    parser.add_argument("--days", type=int, default=1, help="Days back to scan")
    parser.add_argument("--min-confidence", type=int, default=70, help="Minimum confidence to log")
    parser.add_argument("--message", type=str, help="Single message to classify")
    parser.add_argument("--author", type=str, default="unknown", help="Message author")
    parser.add_argument("--context", type=str, default="", help="Previous context")
    parser.add_argument("--summary", action="store_true", help="Show corrections summary")
    
    args = parser.parse_args()
    
    if args.summary:
        print(get_recent_corrections_summary())
        return
    
    if args.message:
        # Single message mode
        result = process_incoming_message(
            message=args.message,
            author=args.author,
            context=args.context
        )
        print(json.dumps(result, indent=2, default=str))
        return
    
    # Scan mode
    results = scan_for_corrections(days_back=args.days, min_confidence=args.min_confidence)
    
    print(f"Scanned: {results['scanned']} conversations")
    print(f"Corrections found: {results['corrections_found']}")
    print(f"Flagged for review: {results['flagged_for_review']}")
    
    if results['corrections']:
        print("\n--- Corrections ---")
        for c in results['corrections']:
            print(f"\n[{c['confidence']}%] {c['author']}: {c['message'][:100]}...")
            print(f"    → {c['reasoning']}")
    
    if results['flagged']:
        print("\n--- Flagged for Review ---")
        for f in results['flagged']:
            print(f"\n[{f['confidence']}%] {f['author']}: {f['message'][:100]}...")


if __name__ == "__main__":
    main()
