#!/usr/bin/env python3
"""
Main test runner for VeriFactu API certificate validation.
Each test case has its own certificate and password.
"""

import json
import os
import shutil
import subprocess
import sys
import time
sys.path.insert(0, os.path.dirname(__file__))

from test_simulate import VeriFactuTester

def clear_cert_storage():
    """Clear certificate storage before tests."""
    storage_path = "data/certs"
    if os.path.exists(storage_path):
        try:
            shutil.rmtree(storage_path)
        except:
            pass
    os.makedirs(storage_path, exist_ok=True)

def main():
    print("=" * 70)
    print("VeriFactu API - Certificate Validation Tests")
    print("=" * 70)
    print()
    
    with open("test_passwords.json", "r") as f:
        passwords = json.load(f)
    
    tester = VeriFactuTester()
    
    tests = [
        {
            "name": "Valid 365 days",
            "cert_file": "test/certs/valid_365days.p12",
            "password": passwords["valid_365days"],
            "expected_success": True,
            "expected_error": None,
            "expected_warning": False,
            "description": "Certificado valido, caduca en 365 dias"
        },
        {
            "name": "Valid 60 days",
            "cert_file": "test/certs/valid_60days.p12",
            "password": passwords["valid_60days"],
            "expected_success": True,
            "expected_error": None,
            "expected_warning": False,
            "description": "Certificado valido, caduca en 60 dias"
        },
        {
            "name": "Expired",
            "cert_file": "test/certs/expired.p12",
            "password": passwords["expired"],
            "expected_success": False,
            "expected_error": "certificate_expired",
            "expected_warning": False,
            "description": "Certificado expirado"
        },
        {
            "name": "Expiring soon",
            "cert_file": "test/certs/expiring_soon.p12",
            "password": passwords["expiring_soon"],
            "expected_success": True,
            "expected_error": None,
            "expected_warning": True,
            "description": "Certificado caduca en menos de 30 dias"
        },
        {
            "name": "Not yet valid",
            "cert_file": "test/certs/not_yet_valid.p12",
            "password": passwords["not_yet_valid"],
            "expected_success": False,
            "expected_error": "certificate_not_yet_valid",
            "expected_warning": False,
            "description": "Certificado no valido aun (fecha futura)"
        },
    ]
    
    passed = 0
    failed = 0
    
    print(f"{'#':<3} {'Test':<20} {'Expected':<10} {'Result':<10} {'Status'}")
    print("-" * 60)
    
    for i, test in enumerate(tests, 1):
        clear_cert_storage()
        time.sleep(0.5)
        
        result = tester.test_certificate(
            test["cert_file"],
            test["password"],
            test["expected_success"] and "PASS" or "FAIL",
            test["name"]
        )
        
        actual_success = result.get("success", False)
        actual_error = result.get("error", "")
        actual_warning = len(result.get("warnings", [])) > 0
        
        expected_str = "PASS" if test["expected_success"] else "FAIL"
        actual_str = "PASS" if actual_success else "FAIL"
        
        passed_test = True
        
        if actual_success != test["expected_success"]:
            passed_test = False
        if test["expected_error"] and actual_error != test["expected_error"]:
            passed_test = False
        if test["expected_warning"] != actual_warning:
            passed_test = False
        
        if passed_test:
            status = "[PASS]"
            passed += 1
        else:
            status = "[FAIL]"
            failed += 1
        
        print(f"{i:<3} {test['name']:<20} {expected_str:<10} {actual_str:<10} {status}")
        
        if not passed_test:
            print(f"      Error: {actual_error or 'none'}")
            print(f"      Warning: {actual_warning}")
    
    print("-" * 60)
    print(f"RESULTS: {passed} passed, {failed} failed")
    print("=" * 70)
    
    return 0 if failed == 0 else 1

if __name__ == "__main__":
    sys.exit(main())