#!/usr/bin/env python3
"""
Kit Validator - LLM-based TIBET token validation
Uses Qwen 32B on P520 GPU node for semantic analysis

By HumoticaOS - Kerst 2025
"""

import requests
import json
from typing import Dict, Any, Tuple

KIT_URL = "http://192.168.4.85:11434"
KIT_MODEL = "qwen2.5:32b"


def validate_token_with_kit(token: Dict[str, Any]) -> Tuple[bool, float, str]:
    """
    Use Kit (Qwen 32B) to validate TIBET token semantically.

    Checks:
    - ERIN (content) consistency
    - ERAAN (dependencies) relevance
    - EROMHEEN (context) plausibility
    - ERACHTER (intent) alignment

    Returns: (is_valid, confidence_score, analysis)
    """

    prompt = f"""Je bent een TIBET token validator. Analyseer dit token op consistentie en authenticiteit.

TOKEN DATA:
- Type: {token.get('type', 'unknown')}
- Actor: {token.get('actor', 'unknown')}
- Timestamp: {token.get('timestamp', 'unknown')}
- State: {token.get('state', 'unknown')}

ERIN (Inhoud): {json.dumps(token.get('erin', {}), ensure_ascii=False)}
ERAAN (Dependencies): {json.dumps(token.get('eraan', []), ensure_ascii=False)}
EROMHEEN (Context): {json.dumps(token.get('eromheen', {}), ensure_ascii=False)}
ERACHTER (Intent): {token.get('erachter', '')}

Analyseer:
1. Is de ERIN consistent met de ERACHTER (intent)?
2. Zijn de ERAAN dependencies relevant?
3. Is de EROMHEEN context plausibel?
4. Zijn er anomalieën of rode vlaggen?

Antwoord in JSON formaat:
{{"valid": true/false, "confidence": 0.0-1.0, "analysis": "korte analyse", "flags": []}}"""

    try:
        response = requests.post(
            f"{KIT_URL}/api/generate",
            json={
                "model": KIT_MODEL,
                "prompt": prompt,
                "stream": False,
                "options": {"temperature": 0.1}  # Low temp for consistent validation
            },
            timeout=30
        )

        if response.ok:
            result = response.json()
            text = result.get("response", "")

            # Parse JSON from response
            try:
                # Find JSON in response
                import re
                json_match = re.search(r'\{[^{}]*\}', text, re.DOTALL)
                if json_match:
                    validation = json.loads(json_match.group())
                    return (
                        validation.get("valid", False),
                        validation.get("confidence", 0.5),
                        validation.get("analysis", "Geen analyse")
                    )
            except json.JSONDecodeError:
                pass

            # Fallback: check for positive keywords
            is_valid = "valid" in text.lower() and "true" in text.lower()
            return (is_valid, 0.5, text[:200])

        return (False, 0.0, f"Kit error: {response.status_code}")

    except requests.exceptions.Timeout:
        return (False, 0.0, "Kit timeout - model may be loading")
    except Exception as e:
        return (False, 0.0, f"Kit connection error: {str(e)}")


def quick_validate(erin: Any, erachter: str) -> Tuple[bool, str]:
    """
    Quick validation: does content match intent?
    Faster than full validation, uses smaller context.
    """

    prompt = f"""Controleer of deze inhoud past bij de intent:

INHOUD: {json.dumps(erin, ensure_ascii=False)[:500]}
INTENT: {erachter}

Past dit? Antwoord alleen: JA of NEE, gevolgd door één zin uitleg."""

    try:
        response = requests.post(
            f"{KIT_URL}/api/generate",
            json={
                "model": "qwen2.5:7b",  # Faster model for quick checks
                "prompt": prompt,
                "stream": False,
                "options": {"temperature": 0.1}
            },
            timeout=10
        )

        if response.ok:
            text = response.json().get("response", "").strip()
            is_valid = text.upper().startswith("JA")
            return (is_valid, text)

        return (False, "Kit niet bereikbaar")

    except Exception as e:
        return (False, str(e))


def check_kit_health() -> Dict[str, Any]:
    """Check if Kit is online and ready."""
    try:
        response = requests.get(f"{KIT_URL}/api/tags", timeout=5)
        if response.ok:
            models = [m["name"] for m in response.json().get("models", [])]
            return {
                "online": True,
                "models": models,
                "has_32b": "qwen2.5:32b" in models,
                "url": KIT_URL
            }
        return {"online": False, "error": f"Status {response.status_code}"}
    except Exception as e:
        return {"online": False, "error": str(e)}


if __name__ == "__main__":
    # Test Kit connection
    print("Checking Kit health...")
    health = check_kit_health()
    print(json.dumps(health, indent=2))

    if health["online"]:
        # Test validation
        test_token = {
            "type": "action",
            "actor": "claude",
            "timestamp": "2025-12-25T12:00:00",
            "state": "CREATED",
            "erin": {"message": "Vrolijk Kerstfeest!"},
            "eraan": ["greeting", "holiday"],
            "eromheen": {"season": "winter", "event": "christmas"},
            "erachter": "Kerstwensen sturen naar het team"
        }

        print("\nValidating test token...")
        valid, confidence, analysis = validate_token_with_kit(test_token)
        print(f"Valid: {valid}")
        print(f"Confidence: {confidence}")
        print(f"Analysis: {analysis}")
