"""
Test upload script for Info Layers
Uploads first 10 records from each layer to test the 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 INFO LAYERS TEST")
print("=" * 60)
print(f"Map ID: {MAP_ID}")
print(f"Temp Directory: {TEMP_DIR}")
print(f"Limit: {LIMIT} records per layer")
print(f"Email: {EMAIL}")
print(f"Fixes Applied:")
print(f"  - Removed JSON-encoding of data field")
print(f"  - Send data as plain 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 each info layer
info_layers = [
    ("cabinet_boundaries.shp", uploader._upload_cabinet_boundaries),
    ("cables.shp", uploader._upload_cables),
    ("parcels.shp", uploader._upload_parcels)
]

for shapefile_name, upload_method in info_layers:
    print(f"📤 Testing {shapefile_name}...")
    shapefile_path = TEMP_DIR / shapefile_name
    if shapefile_path.exists():
        try:
            count, errors = upload_method(shapefile_path, MAP_ID, LIMIT)
            results["uploaded"][shapefile_name] = count
            if errors:
                results["errors"].extend(errors)
            print(f"✅ Uploaded {count} {shapefile_name.replace('.shp', '')} records")
        except Exception as e:
            error_msg = f"Error uploading {shapefile_name}: {str(e)}"
            print(f"❌ {error_msg}")
            results["errors"].append(error_msg)
            results["success"] = False
    else:
        print(f"⚠️  {shapefile_name} not found")

# Display results
print()
print("=" * 60)
print("INFO LAYERS 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)
