#!/usr/bin/env python3
"""
Swirl Master — Smoke Tests
Voer uit na deployment om te verifiëren dat alles werkt.

Gebruik: python3 test_smoke.py [--host http://localhost:5060]
"""

import sys
import json
import requests
import time
from datetime import datetime

# ============================================================
# CONFIG
# ============================================================

HOST = sys.argv[sys.argv.index('--host') + 1] if '--host' in sys.argv else 'http://localhost:5060'
TIMEOUT = 10
PASSED = 0
FAILED = 0
WARNINGS = 0

# ============================================================
# HELPERS
# ============================================================

def test(name, condition, detail=''):
    global PASSED, FAILED
    if condition:
        print(f"  ✅ PASS: {name}")
        PASSED += 1
    else:
        print(f"  ❌ FAIL: {name} {detail}")
        FAILED += 1

def warn(name, detail=''):
    global WARNINGS
    print(f"  ⚠️  WARN: {name} {detail}")
    WARNINGS += 1

def section(title):
    print(f"\n{'='*60}")
    print(f"  {title}")
    print(f"{'='*60}")

# ============================================================
# TESTS
# ============================================================

def test_health():
    section("HEALTH CHECK")
    try:
        r = requests.get(f"{HOST}/api/health", timeout=TIMEOUT)
        data = r.json()
        test("Health endpoint returns 200", r.status_code == 200)
        test("Health status is healthy", data.get('status') == 'healthy')
        test("Database is connected", data.get('database') == True)
        test("Version is 1.0", data.get('version') == '1.0')
        return True
    except requests.exceptions.ConnectionError:
        print(f"  ❌ FATAL: Kan niet verbinden met {HOST}")
        print(f"     Is de server gestart? Check: pm2 status swirl-master")
        return False
    except Exception as e:
        print(f"  ❌ FATAL: {e}")
        return False

def test_static_files():
    section("STATISCHE BESTANDEN")
    try:
        # Index
        r = requests.get(f"{HOST}/", timeout=TIMEOUT)
        test("Index.html laadt", r.status_code == 200 and '<html' in r.text.lower())
        test("Bevat Swirl Master titel", 'Swirl Master' in r.text)

        # CSS
        r = requests.get(f"{HOST}/style.css", timeout=TIMEOUT)
        test("style.css laadt", r.status_code == 200 and len(r.text) > 1000)

        # JS
        r = requests.get(f"{HOST}/app.js", timeout=TIMEOUT)
        test("app.js laadt", r.status_code == 200 and 'RECIPES' in r.text)
    except Exception as e:
        test("Static files", False, str(e))

def test_recipes_api():
    section("RECEPTEN API")
    try:
        # Alle recepten
        r = requests.get(f"{HOST}/api/recipes", timeout=TIMEOUT)
        data = r.json()
        test("GET /api/recipes returns 200", r.status_code == 200)
        test("Response heeft count", 'count' in data)
        test("Response heeft recipes array", 'recipes' in data)
        test("Minimaal 5 recepten in DB", data.get('count', 0) >= 5, f"(got {data.get('count', 0)})")

        # Type filter
        r = requests.get(f"{HOST}/api/recipes?type=ice_cream", timeout=TIMEOUT)
        data = r.json()
        test("Filter op type=ice_cream werkt", all(rec['type'] == 'ice_cream' for rec in data.get('recipes', [])))

        # Diet filter
        r = requests.get(f"{HOST}/api/recipes?diet=vegan", timeout=TIMEOUT)
        data = r.json()
        test("Filter op diet=vegan werkt", all('vegan' in rec.get('diet', []) for rec in data.get('recipes', [])))

        # Search
        r = requests.get(f"{HOST}/api/recipes?q=chocolate", timeout=TIMEOUT)
        data = r.json()
        test("Zoek q=chocolate geeft resultaten", data.get('count', 0) > 0)

        # Sort
        r = requests.get(f"{HOST}/api/recipes?sort=rating", timeout=TIMEOUT)
        data = r.json()
        if data.get('recipes'):
            ratings = [rec['rating'] for rec in data['recipes']]
            test("Sort=rating is aflopend", ratings == sorted(ratings, reverse=True))
        else:
            warn("Sort=rating kon niet testen (geen recepten)")

        # Specifiek recept
        r = requests.get(f"{HOST}/api/recipes/ic-vanilla", timeout=TIMEOUT)
        data = r.json()
        test("GET /api/recipes/ic-vanilla", r.status_code == 200 and data.get('id') == 'ic-vanilla')
        test("Recept heeft ingrediënten", len(data.get('ingredients', [])) > 0)
        test("Recept heeft stappen", len(data.get('steps', [])) > 0)
        test("Recept heeft voeding info", 'calories' in data.get('nutrition', {}))

    except Exception as e:
        test("Recipes API", False, str(e))

def test_programs_api():
    section("PROGRAMMA'S API")
    try:
        r = requests.get(f"{HOST}/api/programs", timeout=TIMEOUT)
        data = r.json()
        test("GET /api/programs returns 200", r.status_code == 200)
        test("13 programma's aanwezig", data.get('count') == 13, f"(got {data.get('count')})")

        r = requests.get(f"{HOST}/api/programs/ice_cream", timeout=TIMEOUT)
        data = r.json()
        test("GET /api/programs/ice_cream", r.status_code == 200 and data.get('name') == 'Ice Cream')

        r = requests.get(f"{HOST}/api/programs/nonexistent", timeout=TIMEOUT)
        test("Onbekend programma geeft 404", r.status_code == 404)

    except Exception as e:
        test("Programs API", False, str(e))

def test_favorites_api():
    section("FAVORIETEN API")
    try:
        session_id = f"test-smoke-{int(time.time())}"
        headers = {'X-Session-ID': session_id}

        # Get empty favorites
        r = requests.get(f"{HOST}/api/favorites", headers=headers, timeout=TIMEOUT)
        data = r.json()
        test("Lege favorieten lijst", r.status_code == 200 and data.get('count') == 0)

        # Add favorite
        r = requests.post(f"{HOST}/api/favorites/ic-vanilla", headers=headers, timeout=TIMEOUT)
        test("Favoriet toevoegen", r.status_code == 200 and r.json().get('status') == 'added')

        # Verify
        r = requests.get(f"{HOST}/api/favorites", headers=headers, timeout=TIMEOUT)
        data = r.json()
        test("Favoriet aanwezig", data.get('count') == 1)

        # Remove
        r = requests.delete(f"{HOST}/api/favorites/ic-vanilla", headers=headers, timeout=TIMEOUT)
        test("Favoriet verwijderen", r.status_code == 200 and r.json().get('status') == 'removed')

        # Verify empty
        r = requests.get(f"{HOST}/api/favorites", headers=headers, timeout=TIMEOUT)
        test("Favorieten leeg na verwijderen", r.json().get('count') == 0)

    except Exception as e:
        test("Favorites API", False, str(e))

def test_mixmatch_api():
    section("MIX & MATCH API")
    try:
        payload = {"base": "heavy-cream", "flavor": "chocolate", "mixin": "brownie"}
        r = requests.post(f"{HOST}/api/mixmatch/suggest", json=payload, timeout=TIMEOUT)
        data = r.json()
        test("POST /api/mixmatch/suggest returns 200", r.status_code == 200)
        test("Heeft compatibility score", 'compatibility' in data and isinstance(data['compatibility'], int))
        test("Heeft ingrediënten", len(data.get('ingredients', [])) > 0)
        test("Heeft stappen", len(data.get('steps', [])) > 0)
        test("Heeft programma aanbeveling", 'program' in data)

    except Exception as e:
        test("Mix & Match API", False, str(e))

def test_stats_api():
    section("STATS API")
    try:
        r = requests.get(f"{HOST}/api/stats", timeout=TIMEOUT)
        data = r.json()
        test("GET /api/stats returns 200", r.status_code == 200)
        test("Heeft totalRecipes", 'totalRecipes' in data and data['totalRecipes'] > 0)
        test("Heeft recipesByType", 'recipesByType' in data)
        test("Version is 1.0", data.get('version') == '1.0')

    except Exception as e:
        test("Stats API", False, str(e))

def test_edge_cases():
    section("EDGE CASES")
    try:
        # Non-existent recipe
        r = requests.get(f"{HOST}/api/recipes/nonexistent-id", timeout=TIMEOUT)
        test("Onbekend recept geeft 404", r.status_code == 404)

        # Invalid rating
        r = requests.post(f"{HOST}/api/ratings/ic-vanilla", json={"rating": 10}, timeout=TIMEOUT)
        test("Ongeldige rating (10) geeft 400", r.status_code == 400)

        # Missing required fields
        r = requests.post(f"{HOST}/api/recipes", json={"name": "Test"}, timeout=TIMEOUT)
        test("Missende fields geeft 400", r.status_code == 400)

        # Empty mixmatch
        r = requests.post(f"{HOST}/api/mixmatch/suggest", json={}, timeout=TIMEOUT)
        test("Lege mixmatch geeft 200 met defaults", r.status_code == 200)

    except Exception as e:
        test("Edge cases", False, str(e))

# ============================================================
# MAIN
# ============================================================

def main():
    print(f"\n🍦 Swirl Master — Smoke Tests")
    print(f"   Host: {HOST}")
    print(f"   Tijd: {datetime.now().isoformat()}")
    print(f"   {'─'*60}")

    if not test_health():
        print(f"\n❌ FATAAL: Server niet bereikbaar. Stop tests.")
        sys.exit(1)

    test_static_files()
    test_recipes_api()
    test_programs_api()
    test_favorites_api()
    test_mixmatch_api()
    test_stats_api()
    test_edge_cases()

    section("SAMENVATTING")
    total = PASSED + FAILED + WARNINGS
    print(f"  Totaal: {total} testen")
    print(f"  ✅ Pass: {PASSED}")
    print(f"  ❌ Fail: {FAILED}")
    print(f"  ⚠️  Warn: {WARNINGS}")

    if FAILED > 0:
        print(f"\n❌ {FAILED} test(en) gefaald. Controleer de output hierboven.")
        sys.exit(1)
    else:
        print(f"\n✅ Alle testen geslaagd! Swirl Master is ready to serve. 🍦")
        sys.exit(0)

if __name__ == '__main__':
    main()
