#!/usr/bin/env python3
"""
Script de test para diagnosticar problemas con la API.
"""

import requests
import json
from pathlib import Path

API_BASE_URL = "https://mercedesbenz.fresbe.com"  # Cambia esto si es necesario

def test_authentication():
    """Test 1: Autenticación"""
    print("\n" + "="*60)
    print("TEST 1: AUTENTICACIÓN")
    print("="*60)

    url = f"{API_BASE_URL}/api/login"
    payload = {
        "email": "javiercabellos@fresbe.com",
        "password": "password",
        "device_name": "test-device"
    }

    print(f"\n→ POST {url}")
    print(f"  Payload: {json.dumps(payload, indent=2)}")

    response = requests.post(url, json=payload)

    print(f"\n← Status: {response.status_code}")
    print(f"  Headers: {dict(response.headers)}")

    try:
        data = response.json()
        print(f"  Body (JSON): {json.dumps(data, indent=2)}")
        token = data.get("token")
        if token:
            print(f"\n✓ Token obtenido: {token[:20]}...")
            return token
        else:
            print(f"\n✗ No hay token en respuesta")
            return None
    except:
        print(f"  Body (text): {response.text[:500]}")
        return None


def test_get_histories(token):
    """Test 2: Obtener Histories con token"""
    print("\n" + "="*60)
    print("TEST 2: OBTENER HISTORIES")
    print("="*60)

    url = f"{API_BASE_URL}/api/histories"
    headers = {
        "Authorization": f"Bearer {token}",
        "Accept": "application/json"
    }

    print(f"\n→ GET {url}")
    print(f"  Headers: {headers}")

    response = requests.get(url, headers=headers)

    print(f"\n← Status: {response.status_code}")
    print(f"  Content-Type: {response.headers.get('content-type')}")

    try:
        data = response.json()
        print(f"  Body (JSON): {json.dumps(data, indent=2)}")
        return True
    except:
        print(f"  Body (text): {response.text[:500]}")
        return False


def test_create_history_simple(token):
    """Test 3: Crear History sin ficheros"""
    print("\n" + "="*60)
    print("TEST 3: CREAR HISTORY (SIN FICHEROS)")
    print("="*60)

    url = f"{API_BASE_URL}/api/histories"
    headers = {
        "Authorization": f"Bearer {token}",
        "Accept": "application/json"
    }

    data = {
        "name": "test_history_" + str(int(__import__('time').time())),
        "description": "Test history for debugging"
    }

    print(f"\n→ POST {url}")
    print(f"  Headers: {headers}")
    print(f"  Data: {json.dumps(data, indent=2)}")

    response = requests.post(url, headers=headers, data=data)

    print(f"\n← Status: {response.status_code}")
    print(f"  Content-Type: {response.headers.get('content-type')}")

    try:
        result = response.json()
        print(f"  Body (JSON): {json.dumps(result, indent=2)}")
        return True
    except:
        print(f"  Body (text): {response.text[:500]}")
        return False


def test_create_history_with_file(token):
    """Test 4: Crear History con fichero pequeño"""
    print("\n" + "="*60)
    print("TEST 4: CREAR HISTORY (CON FICHERO)")
    print("="*60)

    # Crear archivo de prueba pequeño
    test_file = Path("/tmp/test_file.txt")
    test_file.write_text("Test content for upload")

    url = f"{API_BASE_URL}/api/histories"
    headers = {
        "Authorization": f"Bearer {token}",
        "Accept": "application/json"
    }

    data = {
        "name": "test_history_file_" + str(int(__import__('time').time())),
        "description": "Test history with file"
    }

    files = [
        ('input_files[]', ('test_file.txt', open(str(test_file), 'rb')))
    ]

    print(f"\n→ POST {url}")
    print(f"  Headers: {headers}")
    print(f"  Data: {json.dumps(data, indent=2)}")
    print(f"  Files: test_file.txt (23 bytes)")

    response = requests.post(url, headers=headers, data=data, files=files)

    print(f"\n← Status: {response.status_code}")
    print(f"  Content-Type: {response.headers.get('content-type')}")

    try:
        result = response.json()
        print(f"  Body (JSON): {json.dumps(result, indent=2)}")
        return True
    except:
        print(f"  Body (text): {response.text[:500]}")
        return False


def main():
    print("╔════════════════════════════════════════════════════════════╗")
    print("║  Test de API - Diagnosis                                  ║")
    print("╚════════════════════════════════════════════════════════════╝")
    print(f"\nAPI Base: {API_BASE_URL}")

    # Test 1
    token = test_authentication()
    if not token:
        print("\n✗ Autenticación falló. No se pueden hacer más tests.")
        return False

    # Test 2
    if not test_get_histories(token):
        print("\n⚠ GET /api/histories falló")

    # Test 3
    if not test_create_history_simple(token):
        print("\n⚠ POST /api/histories (simple) falló")

    # Test 4
    if not test_create_history_with_file(token):
        print("\n⚠ POST /api/histories (con fichero) falló")

    print("\n" + "="*60)
    print("FIN DE TESTS")
    print("="*60)


if __name__ == "__main__":
    main()
