#!/usr/bin/env python3
"""
Approval guard for expensive model selection.

When a model switch is requested, this script checks if the target model
requires user approval. If it does, it blocks the switch and logs the event.

Expensive models that require approval:
- qwen/qwen3-235b-a22b (OpenRouter)
- minimax/minimax-m2.5 (OpenRouter)
- minimax/minimax-m2.7 (OpenRouter)
- Any model with estimated cost > $0.01 per request

Usage: Called by auto-model-switch.py before performing a model swap.
Returns: 0 = allowed, 1 = blocked (needs approval)
"""

import json
import os
import sys
from datetime import datetime

# Models that require explicit user approval
APPROVAL_REQUIRED = [
    "qwen/qwen3-235b-a22b",
    "minimax/minimax-m2.5",
    "minimax/minimax-m2.7",
    "openrouter/owl-alpha",  # free but unusual
]

# Models that are cheap enough to auto-allow
AUTO_ALLOW = [
    "qwen/qwen3-coder",
    "qwen/qwen3-coder-flash",
    "qwen/qwen3-coder-next",
    "qwen/qwen3-coder-30b-a3b-instruct",
    "qwen/qwen3.6-plus",
    "moonshotai/kimi-k2.6",
]

LOG_FILE = os.path.expanduser("~/.hermes/logs/approval-guard.log")

def log_event(model, action, reason=""):
    """Log approval guard events."""
    os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
    timestamp = datetime.now().isoformat()
    entry = f"[{timestamp}] {action}: {model} — {reason}\n"
    with open(LOG_FILE, "a") as f:
        f.write(entry)

def check_approval(model_name):
    """
    Check if a model requires approval.
    
    Args:
        model_name: The model identifier (e.g., "qwen/qwen3-235b-a22b")
    
    Returns:
        (allowed: bool, reason: str)
    """
    if not model_name:
        return True, "no model specified"
    
    # Local models are always allowed
    if model_name.endswith(".gguf"):
        return True, "local model"
    
    # Check approval-required list
    if model_name in APPROVAL_REQUIRED:
        log_event(model_name, "BLOCKED", "requires explicit approval")
        return False, f"model '{model_name}' requires explicit approval"
    
    # Check auto-allow list
    if model_name in AUTO_ALLOW:
        log_event(model_name, "ALLOWED", "auto-allowed")
        return True, "auto-allowed"
    
    # Default: allow known OpenRouter models, block unknown expensive ones
    if model_name.startswith("qwen/"):
        log_event(model_name, "ALLOWED", "known qwen model")
        return True, "known qwen model"
    
    log_event(model_name, "ALLOWED", "default allow")
    return True, "default allow"

def main():
    if len(sys.argv) < 2:
        print("Usage: approval-guard.py <model_name>", file=sys.stderr)
        sys.exit(1)
    
    model = sys.argv[1]
    allowed, reason = check_approval(model)
    
    if allowed:
        print(f"ALLOWED: {reason}")
        sys.exit(0)
    else:
        print(f"BLOCKED: {reason}")
        log_event(model, "BLOCKED", reason)
        sys.exit(1)

if __name__ == "__main__":
    main()
