"""Interactive project creation via CLI."""

from __future__ import annotations

import os

from .client import NbenchClient


def run_init(api_url: str, api_key: str) -> dict | None:
    """Walk the user through creating a new project. Returns the created project or None."""
    client = NbenchClient(api_url=api_url, api_key=api_key)

    print("=== Create a new research project ===\n")

    # Name
    name = input("Project name: ").strip()
    if not name:
        print("Error: name is required")
        return None

    # Description
    description = input("Description (what are you optimising?): ").strip()
    if not description:
        print("Error: description is required")
        return None

    # Starting metric
    while True:
        val_str = input("Starting metric value (val_bpb): ").strip()
        try:
            starting_val = float(val_str)
            if starting_val <= 0:
                print("Must be positive")
                continue
            break
        except ValueError:
            print("Must be a number")

    # Hardware (optional)
    hardware = input("Hardware (e.g., 1x H100 80GB) [optional]: ").strip()
    if not hardware:
        hardware = "unspecified"

    # Repo URL (optional)
    repo_url = input("Repo URL [optional]: ").strip() or None

    # Branch (optional)
    branch = input("Branch [optional]: ").strip() or None

    print(f"\nCreating project '{name}'...")

    try:
        result = client.create_project(
            name=name,
            description=description,
            baseline_val_bpb=starting_val,
            hardware=hardware,
            repo_url=repo_url,
            branch_name=branch,
        )
    except Exception as e:
        print(f"Error: {e}")
        return None

    project = result.get("project", {})
    sidecar_key = result.get("sidecar_key", "")

    print(f"\nProject created!")
    print(f"  Slug:        {project.get('slug', '?')}")
    print(f"  ID:          {project.get('id', '?')}")

    if sidecar_key:
        print(f"\n  Sidecar key: {sidecar_key}")
        print(f"  Save this key — it won't be shown again.")
        print(f"\n  To start the sidecar:")
        print(f"    export NB_SIDECAR_KEY={sidecar_key}")
        print(f"    export NB_PROJECT_ID={project.get('id', '?')}")
        print(f"    nbench sidecar --watch results.tsv")

    # Offer to generate repo config files
    generate = input("\nGenerate .nbench.yml and CLAUDE.md in current directory? [Y/n]: ").strip()
    if generate.lower() != 'n':
        from .config import generate_config, generate_claude_md, load_config

        config_content = generate_config()
        with open(".nbench.yml", "w") as f:
            f.write(config_content)
        print("  Created .nbench.yml")

        config = load_config(".")
        claude_content = generate_claude_md(name, project.get('slug', ''), config)
        mode = "a" if os.path.exists("CLAUDE.md") else "w"
        with open("CLAUDE.md", mode) as f:
            if mode == "a":
                f.write("\n\n")
            f.write(claude_content)
        print("  Updated CLAUDE.md")

    return result
