#!/usr/bin/env python3
"""
Test Service Contract Wizard - Basic Verification
===================================================

Tests:
1. Frontend route is accessible
2. API endpoints have correct signatures
3. Wizard service functions can be called
4. Dry-run mode works without database writes
"""

import asyncio
import sys
from decimal import Decimal

# Test imports
print("🔍 Testing imports...")
try:
    from app.timetracking.backend.service_contract_wizard import ServiceContractWizardService
    from app.timetracking.backend.models import (
        ServiceContractWizardData,
        ServiceContractWizardAction,
        TimologTransferRequest,
    )
    print("✅ Service imports OK")
except ImportError as e:
    print(f"❌ Import error: {e}")
    sys.exit(1)

# Test Vtiger service
print("🔍 Testing Vtiger service extensions...")
try:
    from app.services.vtiger_service import get_vtiger_service
    vtiger_svc = get_vtiger_service()
    
    # Check methods exist
    assert hasattr(vtiger_svc, 'get_service_contracts'), "Missing get_service_contracts"
    assert hasattr(vtiger_svc, 'get_service_contract_cases'), "Missing get_service_contract_cases"
    assert hasattr(vtiger_svc, 'get_service_contract_timelogs'), "Missing get_service_contract_timelogs"
    
    print("✅ Vtiger service methods OK")
except Exception as e:
    print(f"❌ Vtiger service error: {e}")
    sys.exit(1)

# Test Klippekort service
print("🔍 Testing Klippekort service...")
try:
    from app.ticket.backend.klippekort_service import KlippekortService
    
    # Check method exists
    assert hasattr(KlippekortService, 'get_active_cards_for_customer'), "Missing get_active_cards_for_customer"
    print("✅ Klippekort service OK")
except Exception as e:
    print(f"❌ Klippekort service error: {e}")
    sys.exit(1)

# Test Pydantic models
print("🔍 Testing Pydantic models...")
try:
    # Try creating a model instance
    action = ServiceContractWizardAction(
        type='archive',
        item_id='test123',
        title='Test Case',
        success=True,
        message='Test message',
        dry_run=True
    )
    assert action.type == 'archive'
    assert action.dry_run == True
    print("✅ Pydantic models OK")
except Exception as e:
    print(f"❌ Model validation error: {e}")
    sys.exit(1)

# Test dry-run case archiving (no database writes)
print("🔍 Testing dry-run case archiving...")
try:
    case_data = {
        'id': 'test_case_123',
        'title': 'Test Case Title',
        'description': 'Test Description',
        'status': 'Open',
        'priority': 'High'
    }
    
    success, message, archived_id = ServiceContractWizardService.archive_case(
        case_data,
        'test_contract_123',
        dry_run=True
    )
    
    assert success == True, "Dry-run archiving failed"
    assert '[DRY RUN]' in message, "Message should indicate dry-run"
    assert archived_id is None, "Dry-run should not return an ID"
    print(f"✅ Dry-run archiving OK: {message}")
except Exception as e:
    print(f"❌ Dry-run archiving error: {e}")
    sys.exit(1)

# Test wizard summary generation
print("🔍 Testing wizard summary...")
try:
    contract_data = {
        'contract_id': 'test_contract',
        'contract_number': 'SC-001',
        'subject': 'Test Contract'
    }
    
    actions = [
        {'type': 'archive', 'success': True},
        {'type': 'transfer', 'success': True},
        {'type': 'archive', 'success': False},
    ]
    
    summary = ServiceContractWizardService.get_wizard_summary(
        contract_data,
        actions,
        dry_run=True
    )
    
    assert summary['cases_archived'] == 1
    assert summary['timelogs_transferred'] == 1
    assert summary['failed_items'] == 1
    assert summary['dry_run'] == True
    print(f"✅ Summary generation OK: {summary['status']}")
except Exception as e:
    print(f"❌ Summary generation error: {e}")
    sys.exit(1)

# Test frontend route exists
print("🔍 Testing frontend route...")
try:
    from app.timetracking.frontend.views import router as frontend_router
    
    # Check route exists
    routes = [r.path for r in frontend_router.routes]
    assert any('service-contract-wizard' in r for r in routes), "Frontend route not found"
    print("✅ Frontend route OK")
except Exception as e:
    print(f"❌ Frontend route error: {e}")
    sys.exit(1)

print("\n" + "="*60)
print("✅ ALL TESTS PASSED - Service Contract Wizard is ready!")
print("="*60)
print("\nNext steps:")
print("1. Start the Hub API server: docker-compose up -d api")
print("2. Access the wizard: http://localhost:8000/timetracking/service-contract-wizard")
print("3. Test with dry-run mode first (checkbox enabled)")
print("4. Then run with live mode to commit changes")
