import asyncio
import sys
from pathlib import Path

from unifi_led_api import grab_token as token_mod
from unifi_led_api import led_logic
from unifi_led_api.app_config import AppConfig


async def run_setup(base_dir: Path):
    print("=== UniFi LED API Setup ===")
    
    env_file = base_dir / ".env"
    if env_file.exists():
        ans = input("An existing .env file was found. Do you want to overwrite it? [y/N]: ").strip().lower()
        if ans not in ("y", "yes"):
            print("Setup cancelled.")
            return

    print("\nPlease enter your UniFi Controller details.")
    controller = input("Controller URL (e.g. https://192.168.1.1): ").strip()
    if not controller:
        sys.exit("Controller URL is required.")
        
    user = input("Username (Local account, no 2FA): ").strip()
    if not user:
        sys.exit("Username is required.")
        
    password = input("Password: ").strip()
    if not password:
        sys.exit("Password is required.")
        
    site = input("Site ID [default]: ").strip() or "default"
    
    verify_ssl_ans = input("Verify SSL Certificate? [y/N]: ").strip().lower()
    verify_ssl = verify_ssl_ans in ("y", "yes")

    print("\nStarting device discovery...")
    
    # Create temp config to fetch tokens
    temp_config = AppConfig(
        controller=controller,
        user=user,
        password=password,
        device_ids=[],
        site=site,
        verify_ssl=verify_ssl,
        timeout=10
    )
    
    try:
        session, csrf = await token_mod.get_session(temp_config)
    except Exception as e:
        sys.exit(f"\nFailed to connect to controller: {e}")

    try:
        devices = await led_logic.discover_devices(session, temp_config.controller, temp_config.site)
    except Exception as e:
        await session.close()
        sys.exit(f"\nFailed to discover devices: {e}")
    finally:
        await session.close()

    if not devices:
        sys.exit("\nNo devices found on this controller/site.")

    print("\nDiscovered Devices:")
    for idx, d in enumerate(devices, start=1):
        name = d.get("name", d.get("mac", "Unknown"))
        mac = d.get("mac", "N/A")
        model = d.get("model", "N/A")
        has_toggle = "✅" if "led_override" in d else "❌"
        print(f"  {idx}) [{has_toggle}] {name} ({model} - {mac})")

    print("\nEnter the numbers of the devices you want to control, separated by commas.")
    print("Example: 1,3,4. Or type 'all' to select all.")
    selection = input("Selection [all]: ").strip().lower()

    selected_ids = []
    if not selection or selection == "all":
        for d in devices:
            if "_id" in d:
                selected_ids.append(d["_id"])
                if "led_override" not in d:
                    name = d.get("name", d.get("mac", "Unknown"))
                    print(f"Warning: Selected device '{name}' (❌) does not appear to natively support LED toggling.")
    else:
        try:
            indices = [int(x.strip()) - 1 for x in selection.split(",") if x.strip()]
            for idx in indices:
                if 0 <= idx < len(devices):
                    d = devices[idx]
                    selected_ids.append(d["_id"])
                    if "led_override" not in d:
                        name = d.get("name", d.get("mac", "Unknown"))
                        print(f"Warning: Selected device '{name}' (❌) does not appear to natively support LED toggling.")
                else:
                    print(f"Warning: Selection '{idx+1}' is out of range and will be ignored.")
        except ValueError:
            sys.exit("Invalid selection format. Must be comma-separated numbers.")

    if not selected_ids:
        sys.exit("No valid devices selected. Setup cancelled.")

    # Write to .env
    env_content = f"""# UniFi LED API Configuration
# Automatically generated by 'python start.py setup'

UNIFI_CONTROLLER={controller}
UNIFI_USER={user}
UNIFI_PASS={password}
UNIFI_SITE={site}
UNIFI_VERIFY_SSL={'true' if verify_ssl else 'false'}
UNIFI_DEVICE_ID={','.join(selected_ids)}
"""
    env_file.write_text(env_content, encoding="utf-8")
    
    print("\n.env file successfully created!")
    print("Verifying configuration load...")
    try:
        final_config = AppConfig.load()
        print(f"✅ Configuration verified! Loaded {len(final_config.device_ids)} devices.")
        print("\nYou can now run commands like: python start.py led on")
    except Exception as e:
        print(f"❌ Configuration verification failed: {e}")
