import subprocess

import click

from hatchdx.scaffolder import ScaffoldContext
from hatchdx.scaffolder.engine import scaffold
from hatchdx.scaffolder.prompts import (
    LANGUAGES,
    TEMPLATES,
    TRANSPORTS,
    collect_prompts,
    _get_git_author,
)
from hatchdx.utils import console
from hatchdx.utils.naming import validate_server_name
from hatchdx.utils.workspace import detect_output_dir


def _git_init(project_dir):
    """Initialize a git repository in the project directory."""
    try:
        subprocess.run(
            ["git", "init"],
            cwd=project_dir,
            capture_output=True,
            timeout=10,
        )
        return True
    except (subprocess.SubprocessError, FileNotFoundError):
        return False


@click.command("init")
@click.option("--name", help="Server name (e.g., weather-mcp)")
@click.option(
    "--language",
    type=click.Choice(LANGUAGES, case_sensitive=False),
    help="Programming language",
)
@click.option(
    "--transport",
    type=click.Choice(TRANSPORTS, case_sensitive=False),
    help="MCP transport type",
)
@click.option(
    "--template",
    type=click.Choice(TEMPLATES, case_sensitive=False),
    help="Project template",
)
@click.option("--description", help="Server description")
@click.option("--author", help="Author name")
def init_cmd(name, language, transport, template, description, author):
    """Create a new MCP server project."""
    # If all required flags are provided, skip interactive prompts
    if name and language and transport and template:
        valid, reason = validate_server_name(name)
        if not valid:
            console.error(f"Invalid server name: {reason}")
            raise SystemExit(1)

        context = ScaffoldContext.from_user_input(
            server_name=name,
            language=language,
            transport=transport,
            template=template,
            description=description or "",
            author=author or _get_git_author(),
        )
    else:
        context = collect_prompts()

    # Detect workspace context for output directory
    output_parent = detect_output_dir("server")

    console.step(f"Creating {context.server_name}...")

    try:
        project_dir = scaffold(context, output_parent=output_parent)
    except FileExistsError:
        console.error(f"Directory already exists: {context.server_name}")
        raise SystemExit(1)
    except FileNotFoundError as e:
        console.error(str(e))
        raise SystemExit(1)

    if _git_init(project_dir):
        console.success("Initialized git repository")

    console.success(f"Created {context.server_name}/")

    # Print next steps
    click.echo()
    click.echo("Next steps:")
    click.echo(f"  cd {context.server_name}")
    click.echo("  uv sync")
    click.echo("  hdx server test")
    click.echo("  hdx server dev")
