#!/usr/bin/env python3
"""
Test script to verify training API endpoints
"""

import requests
import json

API_BASE = "http://localhost:8000/api"

def test_training_labels():
    """Test /api/training/labels endpoint"""
    print("=" * 70)
    print("TEST 1: Getting training labels")
    print("=" * 70)
    
    response = requests.get(f"{API_BASE}/training/labels")
    if response.ok:
        data = response.json()
        print(f"✅ Success! Found {data['count']} labels:")
        for label in data['labels']:
            print(f"  {label['code']}: {label['name']}")
    else:
        print(f"❌ Error: {response.status_code}")
    print()

def test_training_files():
    """Test /api/training/files endpoint"""
    print("=" * 70)
    print("TEST 2: Getting training files")
    print("=" * 70)
    
    response = requests.get(f"{API_BASE}/training/files")
    if response.ok:
        data = response.json()
        print(f"✅ Success! Found {data['count']} training files:")
        for file in data['files']:
            print(f"\n  📄 {file['filename']}")
            print(f"     Size: {file['size_mb']} MB")
            if 'point_count' in file:
                print(f"     Points: {file['point_count']}")
                print(f"     Label column: {file.get('label_column', 'N/A')}")
                print(f"     Unique labels: {file.get('label_count', 0)}")
    else:
        print(f"❌ Error: {response.status_code}")
    print()

def test_shapefile_labels(filename="ST_training data_updated_1130points_new.shp"):
    """Test /api/training/shapefile/{filename}/labels endpoint"""
    print("=" * 70)
    print(f"TEST 3: Getting labels from shapefile: {filename}")
    print("=" * 70)
    
    response = requests.get(f"{API_BASE}/training/shapefile/{filename}/labels")
    if response.ok:
        data = response.json()
        print(f"✅ Success!")
        print(f"  Filename: {data['filename']}")
        print(f"  Points: {data['point_count']}")
        print(f"  Label column: {data['label_column']}")
        print(f"  Unique labels: {data['label_count']}")
        print(f"  Bbox: {data['bbox']}")
        print(f"\n  Labels distribution:")
        for label in data['labels']:
            mapped = "✅" if label['mapped'] else "⚠️"
            print(f"    {mapped} {label['name']}: {label['count']} points (code: {label['code']})")
    else:
        print(f"❌ Error: {response.status_code}")
        print(response.text)
    print()

def test_config_presets():
    """Test /api/config/presets endpoint"""
    print("=" * 70)
    print("TEST 4: Getting config presets")
    print("=" * 70)
    
    response = requests.get(f"{API_BASE}/config/presets")
    if response.ok:
        data = response.json()
        print(f"✅ Success! Found {len(data['presets'])} presets:")
        for preset in data['presets']:
            print(f"\n  📋 {preset['name']}")
            config = preset['config']
            print(f"     Bbox: [{config['min_lon']}, {config['min_lat']}, {config['max_lon']}, {config['max_lat']}]")
            print(f"     Time: {config['start_date']} → {config['end_date']}")
            print(f"     Resolution: {config['resolution']}m")
    else:
        print(f"❌ Error: {response.status_code}")
    print()

if __name__ == "__main__":
    print("\n" + "=" * 70)
    print("🧪 TESTING TRAINING API ENDPOINTS")
    print("=" * 70 + "\n")
    
    try:
        test_training_labels()
        test_training_files()
        test_shapefile_labels()
        test_config_presets()
        
        print("=" * 70)
        print("✅ ALL TESTS COMPLETED!")
        print("=" * 70)
        
    except requests.exceptions.ConnectionError:
        print("\n❌ Error: Cannot connect to API server")
        print("Make sure the server is running: python api_server.py")
    except Exception as e:
        print(f"\n❌ Error: {e}")
        import traceback
        traceback.print_exc()
