#!/usr/bin/env python3
"""
Pre-flight corrections check.
Run before high-stakes actions to surface relevant corrections.

Usage:
    preflight.py deploy
    preflight.py "create app"
    preflight.py test fixed done
"""

import sys
import json
import subprocess
from pathlib import Path

SKILL_DIR = Path(__file__).parent
RETRIEVE_SCRIPT = SKILL_DIR / "retrieve.py"

# Action -> Keywords mapping for comprehensive retrieval
ACTION_KEYWORDS = {
    "deploy": ["deploy", "production", "release", "cloud run"],
    "test": ["test", "fixed", "done", "qa", "verify"],
    "create": ["create app", "new product", "npm", "pnpm", "template"],
    "design": ["design", "landing page", "ui", "ux", "mobbin", "dribbble"],
    "video": ["video", "animation", "remotion", "motion", "emoji"],
    "firebase": ["firebase", "firestore", "auth", "rules"],
    "branch": ["branch", "checkout", "merge", "rebase", "symphony"],
    "asset": ["asset", "image", "generate", "marketing", "qa"],
    "browser": ["browser", "screenshot", "snapshot", "profile"],
}

def get_keywords_for_action(action: str) -> list:
    """Get relevant keywords for an action."""
    action_lower = action.lower()
    
    # Direct match
    if action_lower in ACTION_KEYWORDS:
        return ACTION_KEYWORDS[action_lower]
    
    # Partial match
    for key, keywords in ACTION_KEYWORDS.items():
        if key in action_lower or action_lower in key:
            return keywords
    
    # Return action itself as keyword
    return [action]

def run_preflight(actions: list) -> dict:
    """Run preflight check for given actions."""
    all_keywords = []
    for action in actions:
        all_keywords.extend(get_keywords_for_action(action))
    
    # Dedupe
    keywords = list(set(all_keywords))
    query = " ".join(keywords)
    
    # Run retrieve.py
    result = subprocess.run(
        [sys.executable, str(RETRIEVE_SCRIPT), query, "--top", "5", "--json"],
        capture_output=True,
        text=True
    )
    
    if result.returncode != 0:
        # Fallback to non-json output
        result = subprocess.run(
            [sys.executable, str(RETRIEVE_SCRIPT), query, "--top", "5"],
            capture_output=True,
            text=True
        )
        return {
            "query": query,
            "raw_output": result.stdout,
            "corrections": []
        }
    
    try:
        corrections = json.loads(result.stdout)
    except json.JSONDecodeError:
        corrections = []
    
    return {
        "query": query,
        "corrections": corrections,
        "raw_output": result.stdout if not corrections else None
    }

def format_output(result: dict) -> str:
    """Format preflight results for display."""
    lines = []
    lines.append("=" * 60)
    lines.append("🚨 PRE-FLIGHT CORRECTIONS CHECK")
    lines.append("=" * 60)
    lines.append(f"Query: {result['query']}")
    lines.append("")
    
    if result.get('raw_output'):
        lines.append(result['raw_output'])
    elif result.get('corrections'):
        for cor in result['corrections']:
            severity_icon = {
                'critical': '🔴',
                'high': '🟠',
                'medium': '🟡',
                'low': '⚪'
            }.get(cor.get('severity', ''), '⚪')
            
            lines.append(f"{severity_icon} {cor.get('id', '?')}: {cor.get('summary', cor.get('title', '?'))}")
            if cor.get('correct_approach'):
                # First line of correct approach
                approach = cor['correct_approach'].strip().split('\n')[0]
                lines.append(f"   → {approach}")
            lines.append("")
    else:
        lines.append("✅ No relevant corrections found for this action.")
    
    lines.append("=" * 60)
    return "\n".join(lines)

def main():
    if len(sys.argv) < 2:
        print("Usage: preflight.py <action> [action2] [action3]")
        print("")
        print("Actions: deploy, test, create, design, video, firebase, branch, asset, browser")
        print("")
        print("Examples:")
        print("  preflight.py deploy")
        print("  preflight.py test fixed")
        print("  preflight.py 'create app'")
        sys.exit(1)
    
    actions = sys.argv[1:]
    result = run_preflight(actions)
    print(format_output(result))

if __name__ == "__main__":
    main()
