"""
Test upload script for Permits
Uploads first 10 records to test the reverse-engineered fix
"""

import os
import sys
from pathlib import Path
from verofy_uploader import VerofyUploader

# Get credentials from environment
EMAIL = os.getenv("VEROFY_USER")
PASSWORD = os.getenv("VEROFY_PASS")

if not EMAIL or not PASSWORD:
    print("❌ Missing environment variables: Please set VEROFY_USER and VEROFY_PASS")
    sys.exit(1)

# Configuration
MAP_ID = 16950
TEMP_DIR = Path("../temp")
LIMIT = 10  # Upload only first 10 records

print("=" * 60)
print("VEROFY API PERMITS TEST")
print("=" * 60)
print(f"Map ID: {MAP_ID}")
print(f"Temp Directory: {TEMP_DIR}")
print(f"Limit: {LIMIT} records")
print(f"Email: {EMAIL}")
print(f"Fixes Applied:")
print(f"  - Added mappermitstatusId: 1")
print(f"  - Added mappermitentitytypeId: 6")
print(f"  - Added mappermitulrtypeId: 3")
print(f"  - Added mappermitentitymeetId: 1")
print(f"  - Added mappermitrequirementsId: 1")
print(f"  - Changed group1 → permitgroup")
print(f"  - Wrapped poly in double array [[...]]")
print("=" * 60)
print()

# Initialize uploader
uploader = VerofyUploader(EMAIL, PASSWORD)

# Authenticate
if not uploader.authenticate():
    print("❌ Authentication failed")
    sys.exit(1)

results = {
    "success": True,
    "uploaded": {},
    "errors": []
}

# Test permits
print("📤 Testing permits.shp...")
shapefile_path = TEMP_DIR / "permits.shp"
if shapefile_path.exists():
    try:
        count, errors = uploader._upload_permits(shapefile_path, MAP_ID, LIMIT)
        results["uploaded"]["permits.shp"] = count
        if errors:
            results["errors"].extend(errors)
        print(f"✅ Uploaded {count} permits")
    except Exception as e:
        error_msg = f"Error uploading permits.shp: {str(e)}"
        print(f"❌ {error_msg}")
        results["errors"].append(error_msg)
        results["success"] = False
else:
    print("⚠️  permits.shp not found")

# Display results
print()
print("=" * 60)
print("PERMITS TEST RESULTS")
print("=" * 60)
print(f"Success: {results['success']}")
print()
print("Uploaded counts:")
for shapefile, count in results.get('uploaded', {}).items():
    print(f"  {shapefile}: {count} records")

if results.get('errors'):
    print()
    print("Errors encountered:")
    for error in results['errors']:
        print(f"  - {error}")

print("=" * 60)
