#!/usr/bin/env python
"""
Focused test script that tests the most important functionality
without getting caught up in serialization format complexities
"""

import sys
from datetime import datetime
from models import (
    UserStatus, UserType, SkillLevel, EmploymentType,
    Candidate, Employer, Location, Skill, AIModelType
)


def test_model_creation():
    """Test that we can create models successfully"""
    print("🧪 Testing model creation...")
    
    # Create supporting objects
    location = Location(city="Austin", country="USA")
    skill = Skill(name="Python", category="Programming", level=SkillLevel.ADVANCED)
    
    # Create candidate
    candidate = Candidate(
        email="test@example.com",
        username="test_candidate",
        createdAt=datetime.now(),
        updatedAt=datetime.now(),
        status=UserStatus.ACTIVE,
        firstName="John",
        lastName="Doe",
        fullName="John Doe",
        skills=[skill],
        experience=[],
        education=[],
        preferredJobTypes=[EmploymentType.FULL_TIME],
        location=location,
        languages=[],
        certifications=[]
    )
    
    # Create employer
    employer = Employer(
        firstName="Mary",
        lastName="Smith",
        fullName="Mary Smith",
        email="hr@company.com",
        username="test_employer",
        createdAt=datetime.now(),
        updatedAt=datetime.now(),
        status=UserStatus.ACTIVE,
        companyName="Test Company",
        industry="Technology",
        companySize="50-200",
        companyDescription="A test company",
        location=location
    )
    
    print(f"✅ Candidate: {candidate.first_name} {candidate.last_name}")
    print(f"✅ Employer: {employer.company_name}")
    print(f"✅ User types: {candidate.user_type}, {employer.user_type}")
    
    return candidate, employer

def test_json_api_format():
    """Test JSON serialization in API format (the most important use case)"""
    print("\n📡 Testing JSON API format...")
    
    candidate, employer = test_model_creation()
    
    # Serialize to JSON (API format)
    candidate_json = candidate.model_dump_json(by_alias=True)
    employer_json = employer.model_dump_json(by_alias=True)
    
    print(f"✅ Candidate JSON: {len(candidate_json)} chars")
    print(f"✅ Employer JSON: {len(employer_json)} chars")
    
    # Deserialize from JSON
    candidate_back = Candidate.model_validate_json(candidate_json)
    employer_back = Employer.model_validate_json(employer_json)
    
    # Verify data integrity
    assert candidate_back.email == candidate.email
    assert candidate_back.first_name == candidate.first_name
    assert employer_back.company_name == employer.company_name
    
    print(f"✅ JSON round-trip successful")
    print(f"✅ Data integrity verified")
    
    return True

def test_api_dict_format():
    """Test dictionary format with aliases (for API requests/responses)"""
    print("\n📊 Testing API dictionary format...")
    
    candidate, employer = test_model_creation()
    
    # Create API format dictionaries
    candidate_dict = candidate.model_dump(by_alias=True)
    employer_dict = employer.model_dump(by_alias=True)
    
    # Verify camelCase aliases are used
    assert "firstName" in candidate_dict
    assert "lastName" in candidate_dict
    assert "createdAt" in candidate_dict
    assert "companyName" in employer_dict
    
    print(f"✅ API format dictionaries created")
    print(f"✅ CamelCase aliases verified")
    
    # Test deserializing from API format
    candidate_back = Candidate.model_validate(candidate_dict)
    employer_back = Employer.model_validate(employer_dict)
    
    assert candidate_back.email == candidate.email
    assert employer_back.company_name == employer.company_name
    
    print(f"✅ API format round-trip successful")
    
    return True

def test_validation_constraints():
    """Test that validation constraints work"""
    print("\n🔒 Testing validation constraints...")

    try:
        # Create a candidate with invalid email
        invalid_candidate = Candidate(
            email="invalid-email",
            username="test_invalid",
            createdAt=datetime.now(),
            updatedAt=datetime.now(),
            status=UserStatus.ACTIVE,
            firstName="Jane",
            lastName="Doe",
            fullName="Jane Doe"
        )
        print("❌ Validation should have failed but didn't")
        return False
    except ValueError as e:
        print(f"✅ Validation error caught: {e}")    
    return True

def test_enum_values():
    """Test that enum values work correctly"""
    print("\n📋 Testing enum values...")
    
    # Test that enum values are properly handled
    candidate, employer = test_model_creation()
    
    # Check enum values in serialization
    candidate_dict = candidate.model_dump(by_alias=True)
    
    assert candidate_dict["status"] == "active"
    assert candidate_dict["userType"] == "candidate"
    assert employer.user_type == UserType.EMPLOYER
    
    print(f"✅ Enum values correctly serialized")
    print(f"✅ User types: candidate={candidate.user_type}, employer={employer.user_type}")
    
    return True

def main():
    """Run all focused tests"""
    print("🎯 Focused Pydantic Model Tests")
    print("=" * 40)
    
    try:
        test_model_creation()
        test_json_api_format()
        test_api_dict_format() 
        test_validation_constraints()
        test_enum_values()
        
        print(f"\n🎉 All focused tests passed!")
        print("=" * 40)
        print("✅ Models work correctly")
        print("✅ JSON API format works")
        print("✅ Validation constraints work")
        print("✅ Enum values work")
        print("✅ Ready for type generation!")
        
        return True
        
    except Exception as e:
        print(f"\n❌ Test failed: {type(e).__name__}: {e}")
        import traceback
        traceback.print_exc()
        print(f"\n❌ {traceback.format_exc()}")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)