#!/usr/bin/env python3
"""
Test script for tkinter directory selector
"""

import tkinter as tk
from tkinter import filedialog
import threading
import queue
import requests
import json


def test_tkinter_directly():
    """Test tkinter directory dialog directly"""
    print("Testing tkinter directly...")

    root = tk.Tk()
    root.withdraw()  # Hide main window
    root.attributes("-topmost", True)  # Keep on top

    selected_path = filedialog.askdirectory(
        title="Test - Seleccionar Directorio", initialdir="D:\\"
    )

    root.destroy()

    if selected_path:
        print(f"✅ Selected directory: {selected_path}")
        return selected_path
    else:
        print("❌ User cancelled or no directory selected")
        return None


def test_api_endpoint():
    """Test the Flask API endpoint"""
    print("\nTesting Flask API endpoint...")

    url = "http://localhost:5120/api/directories/select"
    data = {"initial_dir": "D:\\", "title": "Test API - Seleccionar Directorio"}

    try:
        print("Making POST request to:", url)
        response = requests.post(url, json=data, timeout=35)

        print(f"Response status: {response.status_code}")
        result = response.json()
        print(f"Response data: {json.dumps(result, indent=2)}")

        if response.status_code == 200:
            if result.get("success") and result.get("selected_path"):
                print(f"✅ API Test Success: {result['selected_path']}")
            else:
                print(f"ℹ️  API Test: {result.get('message', 'No directory selected')}")
        else:
            print(f"❌ API Test Failed: {result.get('error', 'Unknown error')}")

    except requests.exceptions.Timeout:
        print("⏰ Request timed out (this is expected if dialog was cancelled)")
    except Exception as e:
        print(f"❌ Error testing API: {e}")


if __name__ == "__main__":
    print("=== Testing Directory Selector Functionality ===\n")

    # Test 1: Direct tkinter test
    test_tkinter_directly()

    # Test 2: API endpoint test
    test_api_endpoint()

    print("\n=== Tests completed ===")
