"""Edge case tests for ADFMentor validation and error handling."""

import os
from dotenv import load_dotenv
from ADFMentor import ADFMentor

load_dotenv()


def test_empty_zip():
    """Test empty ZIP file (should fail gracefully)."""
    print("\n" + "="*70)
    print("EDGE CASE 1: Empty ZIP")
    print("="*70)
    
    # Create empty ZIP for testing
    import zipfile
    with zipfile.ZipFile("test_empty.zip", "w") as z:
        pass
    
    mentor = ADFMentor(api_key=os.getenv("GEMINI_API_KEY"))
    result = mentor.evaluate_adf("test_empty.zip")
    
    print(f"Score: {result['score']}")
    print(f"Feedback: {result['feedback']}")
    assert result['score'] == 0, "Empty ZIP should score 0"
    print("✅ Correctly rejected empty ZIP")


def test_invalid_json():
    """Test ZIP with invalid JSON (should fail gracefully)."""
    print("\n" + "="*70)
    print("EDGE CASE 2: Invalid JSON")
    print("="*70)
    
    # Create ZIP with broken JSON
    import zipfile
    import tempfile
    import os
    
    with tempfile.TemporaryDirectory() as tmpdir:
        broken_json = os.path.join(tmpdir, "pipeline.json")
        with open(broken_json, "w") as f:
            f.write('{"name": "broken", invalid json here}')
        
        with zipfile.ZipFile("test_invalid.zip", "w") as z:
            z.write(broken_json, "pipeline.json")
    
    mentor = ADFMentor(api_key=os.getenv("GEMINI_API_KEY"))
    result = mentor.evaluate_adf("test_invalid.zip")
    
    print(f"Score: {result['score']}")
    print(f"Feedback: {result['feedback']}")
    assert result['score'] == 0, "Invalid JSON should score 0"
    print("✅ Correctly rejected invalid JSON")


def test_non_json_files():
    """Test ZIP with non-JSON files like .xlsx (should fail)."""
    print("\n" + "="*70)
    print("EDGE CASE 3: ZIP with .xlsx file")
    print("="*70)
    
    import zipfile
    import tempfile
    import os
    
    with tempfile.TemporaryDirectory() as tmpdir:
        excel_file = os.path.join(tmpdir, "data.xlsx")
        with open(excel_file, "wb") as f:
            f.write(b"fake excel content")
        
        with zipfile.ZipFile("test_excel.zip", "w") as z:
            z.write(excel_file, "data.xlsx")
    
    mentor = ADFMentor(api_key=os.getenv("GEMINI_API_KEY"))
    result = mentor.evaluate_adf("test_excel.zip")
    
    print(f"Score: {result['score']}")
    print(f"Feedback: {result['feedback']}")
    assert result['score'] == 0, "Non-JSON files should be rejected"
    assert "non-JSON files" in result['feedback'].lower()
    print("✅ Correctly rejected non-JSON files")


def test_missing_file():
    """Test non-existent file path (should fail gracefully)."""
    print("\n" + "="*70)
    print("EDGE CASE 4: Non-existent file")
    print("="*70)
    
    mentor = ADFMentor(api_key=os.getenv("GEMINI_API_KEY"))
    result = mentor.evaluate_adf("does_not_exist.zip")
    
    print(f"Score: {result['score']}")
    print(f"Feedback: {result['feedback']}")
    assert result['score'] == 0, "Missing file should score 0"
    assert "not found" in result['feedback'].lower()
    print("✅ Correctly handled missing file")


def test_huge_zip():
    """Test ZIP exceeding size limits (should fail)."""
    print("\n" + "="*70)
    print("EDGE CASE 5: ZIP too large (>50MB)")
    print("="*70)
    
    import zipfile
    import tempfile
    import os
    
    with tempfile.TemporaryDirectory() as tmpdir:
        # Create a 60MB file
        large_json = os.path.join(tmpdir, "huge.json")
        with open(large_json, "w") as f:
            f.write('{"data": "' + 'x' * (60 * 1024 * 1024) + '"}')
        
        with zipfile.ZipFile("test_huge.zip", "w") as z:
            z.write(large_json, "huge.json")
    
    mentor = ADFMentor(api_key=os.getenv("GEMINI_API_KEY"))
    result = mentor.evaluate_adf("test_huge.zip")
    
    print(f"Score: {result['score']}")
    print(f"Feedback: {result['feedback']}")
    assert result['score'] == 0, "Huge ZIP should be rejected"
    print("✅ Correctly rejected oversized ZIP")


if __name__ == "__main__":
    print("\n" + "="*70)
    print("EDGE CASE TESTING - Validation & Error Handling")
    print("="*70)
    
    try:
        test_empty_zip()
        test_invalid_json()
        test_non_json_files()
        test_missing_file()
        test_huge_zip()
        
        print("\n" + "="*70)
        print("✅ ALL EDGE CASE TESTS PASSED!")
        print("="*70)
    except AssertionError as e:
        print(f"\n❌ TEST FAILED: {e}")
    except Exception as e:
        print(f"\n❌ UNEXPECTED ERROR: {e}")
    finally:
        # Cleanup test files
        import os
        for f in ["test_empty.zip", "test_invalid.zip", "test_excel.zip", "test_huge.zip"]:
            if os.path.exists(f):
                os.remove(f)
