import subprocess

import click

from hatchdx.scaffolder import ScaffoldContext
from hatchdx.utils.naming import validate_server_name


LANGUAGES = ["python", "typescript"]
TRANSPORTS = ["stdio", "http"]
TEMPLATES = ["minimal", "api-wrapper", "database", "file-ops"]


def _get_git_author() -> str:
    try:
        result = subprocess.run(
            ["git", "config", "user.name"],
            capture_output=True,
            text=True,
            timeout=5,
        )
        return result.stdout.strip()
    except (subprocess.SubprocessError, FileNotFoundError):
        return ""


def _prompt_server_name() -> str:
    while True:
        name = click.prompt("Server name (e.g., weather-mcp)")
        valid, reason = validate_server_name(name)
        if valid:
            return name
        click.echo(f"  Invalid: {reason}. Use lowercase letters, numbers, and hyphens.")


def collect_prompts() -> ScaffoldContext:
    """Run interactive prompts and return a ScaffoldContext."""
    click.echo()
    server_name = _prompt_server_name()
    language = click.prompt(
        "Language",
        type=click.Choice(LANGUAGES, case_sensitive=False),
        default="python",
    )
    transport = click.prompt(
        "Transport",
        type=click.Choice(TRANSPORTS, case_sensitive=False),
        default="stdio",
    )
    template = click.prompt(
        "Template",
        type=click.Choice(TEMPLATES, case_sensitive=False),
        default="minimal",
    )
    description = click.prompt("Description", default="")
    author = click.prompt("Author", default=_get_git_author())

    return ScaffoldContext.from_user_input(
        server_name=server_name,
        language=language,
        transport=transport,
        template=template,
        description=description,
        author=author,
    )
