#!/usr/bin/env python3
import json
import os
from pathlib import Path

from lex.tools.project_root import find_project_root  # shared utility


LEX_CONFIG_PREFIX = "lex: "


def _build_launch_configuration(name, args, envs=None):
    config = {
        "name": f"{LEX_CONFIG_PREFIX}{name}",
        "type": "debugpy",
        "request": "launch",
        "module": "lex",
        "args": args,
        "envFile": "${workspaceFolder}/.env",
        "cwd": "${workspaceFolder}",
        "env": {"PYTHONUNBUFFERED": "1", **(envs or {})},
        "console": "integratedTerminal",
    }
    return config


def generate_vscode_configs(project_root=None):
    start = project_root or os.getcwd()
    project_root = os.path.abspath(find_project_root(start))

    vscode_dir = os.path.join(project_root, ".vscode")
    os.makedirs(vscode_dir, exist_ok=True)

    env_file_path = os.path.join(project_root, ".env")

    configs = [
        _build_launch_configuration("Init", ["init"]),
        _build_launch_configuration("Setup With AI", ["setup-with-ai"]),
        _build_launch_configuration(
            "Start",
            ["start", "--reload", "--loop", "asyncio", "lex_app.asgi:application"],
        ),
        _build_launch_configuration("Flower", ["flower"]),
        _build_launch_configuration(
            "Celery Workers",
            ["celery-workers", "${input:lexCeleryWorkerCount}"],
            envs={"IS_RUNNING_IN_CELERY": "true", "CELERY_ACTIVE": "true"},
        ),
        _build_launch_configuration("Make Migrations", ["makemigrations"]),
        _build_launch_configuration("Migrate", ["migrate"]),
        _build_launch_configuration(
            "Streamlit", ["streamlit", "run", "streamlit_app.py"]
        ),
        _build_launch_configuration("Create DB", ["create_db"]),
        _build_launch_configuration("Flush DB", ["flush"]),
    ]

    inputs = [
        {
            "id": "lexCeleryWorkerCount",
            "type": "promptString",
            "description": "Worker count",
            "default": "1",
        }
    ]

    launch_json_path = os.path.join(vscode_dir, "launch.json")

    # Merge with existing launch.json if present
    existing_configs = []
    existing_inputs = []
    if os.path.exists(launch_json_path):
        try:
            with open(launch_json_path, "r", encoding="utf-8") as f:
                existing = json.load(f)
            # Keep existing configs that are NOT lex-managed
            existing_configs = [
                c
                for c in existing.get("configurations", [])
                if not c.get("name", "").startswith(LEX_CONFIG_PREFIX)
            ]
            # Keep existing inputs that are NOT lex-managed
            existing_inputs = [
                i
                for i in existing.get("inputs", [])
                if not i.get("id", "").startswith("lex")
            ]
        except (json.JSONDecodeError, KeyError):
            pass

    launch_json = {
        "version": "0.2.0",
        "configurations": existing_configs + configs,
    }
    all_inputs = existing_inputs + inputs
    if all_inputs:
        launch_json["inputs"] = all_inputs

    with open(launch_json_path, "w", encoding="utf-8") as f:
        json.dump(launch_json, f, indent=2)
        f.write("\n")

    print(f"Generating VS Code launch configurations in: {vscode_dir}")
    print(f"Project root: {project_root}")
    for config in configs:
        print(f"[OK] Generated: {config['name']}")
    print("\nVS Code launch configurations generated successfully!")
    if os.path.exists(env_file_path):
        print(f"[OK] Configurations will use .env file: {env_file_path}")
    else:
        print(f"[WARN] No .env file found at {env_file_path}")
        print("  Create one if you need environment variables for your project.")


if __name__ == "__main__":
    import argparse
    import sys

    parser = argparse.ArgumentParser(
        description="Generate VS Code launch configurations for lex-app projects"
    )
    parser.add_argument(
        "-p",
        "--project-root",
        help="Project root directory (default: execution directory)",
    )
    args = parser.parse_args()
    try:
        generate_vscode_configs(args.project_root)
    except Exception as e:
        print(f"Error generating configurations: {e}")
        sys.exit(1)
