"""hdx init — scaffold a new HatchDX workspace."""

import subprocess
from pathlib import Path

import click

from hatchdx.utils import console
from hatchdx.utils.workspace import WORKSPACE_MARKER


_WORKSPACE_TOML_TEMPLATE = """\
# HatchDX workspace configuration
# https://github.com/ceasarb/hatchdx

[workspace]
name = "{name}"
"""

_GITIGNORE_TEMPLATE = """\
# Python
__pycache__/
*.pyc
*.egg-info/
dist/
build/
.venv/

# Node
node_modules/

# HatchDX
.hdx/

# IDE
.vscode/
.idea/

# OS
.DS_Store
"""

_README_TEMPLATE = """\
# {name}

A [HatchDX](https://github.com/ceasarb/hatchdx) workspace.

## Getting Started

```bash
# Create a new MCP server
hdx server create

# Create a new AI agent
hdx agent create
```

## Structure

```
{name}/
├── hdx-workspace.toml
├── servers/          # MCP server projects
└── agents/           # AI agent configurations
```
"""


def _git_init(project_dir: Path) -> bool:
    """Initialize a git repository."""
    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.argument("name", required=False)
def workspace_init_cmd(name: str | None) -> None:
    """Scaffold a new HatchDX workspace.

    Creates a workspace directory with servers/ and agents/ subdirectories.
    """
    if not name:
        name = click.prompt("Workspace name")

    name = name.strip()
    if not name:
        console.error("Workspace name cannot be empty.")
        raise SystemExit(1)

    target = Path.cwd() / name
    if target.exists():
        console.error(f"Directory already exists: {name}")
        raise SystemExit(1)

    console.step(f"Creating workspace {name}...")

    # Create directory structure
    target.mkdir()
    (target / "servers").mkdir()
    (target / "agents").mkdir()

    # Write workspace marker
    (target / WORKSPACE_MARKER).write_text(
        _WORKSPACE_TOML_TEMPLATE.format(name=name)
    )

    # Write .gitignore
    (target / ".gitignore").write_text(_GITIGNORE_TEMPLATE)

    # Write README
    (target / "README.md").write_text(_README_TEMPLATE.format(name=name))

    # Initialize git
    if _git_init(target):
        console.success("Initialized git repository")

    console.success(f"Created workspace {name}/")

    click.echo()
    click.echo("Next steps:")
    click.echo(f"  cd {name}")
    click.echo("  hdx server create")
    click.echo("  hdx agent create")
