"""nestdx init — initialize a new NestDX workspace."""

from __future__ import annotations

from importlib import resources
from pathlib import Path

import click

from nestdx.config.parser import CONFIG_FILENAME
from nestdx.utils.console import console


TEMPLATES_PKG = "nestdx.config.templates"
VALID_TEMPLATES = ("default", "python", "typescript")

CI_WORKFLOW_TEMPLATE = """\
name: NestDX Audit
on: [pull_request]
permissions:
  security-events: write
  contents: read
jobs:
  audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: actions/setup-python@v5
        with:
          python-version: "3.13"
      - run: pip install nestdx
      - name: Run NestDX audit
        run: |
          nestdx audit --ci \\
            --base-ref ${{ github.event.pull_request.base.sha }} \\
            --head-ref ${{ github.event.pull_request.head.sha }} \\
            --format sarif \\
            > nestdx-results.sarif
      - name: Upload SARIF
        if: always()
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: nestdx-results.sarif
"""


def _load_template(template_name: str) -> str:
    ref = resources.files(TEMPLATES_PKG).joinpath(f"{template_name}.yaml")
    return ref.read_text(encoding="utf-8")


def _ensure_nestdx_dir(project_root: Path) -> Path:
    nestdx_dir = project_root / ".nestdx"
    sessions_dir = nestdx_dir / "sessions"
    sessions_dir.mkdir(parents=True, exist_ok=True)
    return nestdx_dir


def _update_gitignore(project_root: Path) -> None:
    gitignore = project_root / ".gitignore"
    entry = ".nestdx/"

    if gitignore.exists():
        content = gitignore.read_text()
        if entry in content:
            return
        if not content.endswith("\n"):
            content += "\n"
        content += f"\n# NestDX session data\n{entry}\n"
        gitignore.write_text(content)
    else:
        gitignore.write_text(f"# NestDX session data\n{entry}\n")


@click.command()
@click.argument("name", required=False)
@click.option(
    "--template", "-t",
    type=click.Choice(VALID_TEMPLATES),
    default="default",
    help="Project template to use.",
)
@click.option("--force", is_flag=True, help="Overwrite existing nestdx.yaml.")
@click.option("--ci", is_flag=True, help="Also generate GitHub Actions workflow for CI auditing.")
def init_cmd(name: str | None, template: str, force: bool, ci: bool):
    """Initialize a NestDX workspace in the current directory."""
    project_root = Path.cwd()
    config_path = project_root / CONFIG_FILENAME

    if config_path.exists() and not force:
        console.print(
            f"[yellow]{CONFIG_FILENAME} already exists.[/yellow] Use --force to overwrite."
        )
        raise SystemExit(1)

    # Determine project name
    project_name = name or project_root.name

    # Load and render template
    raw_template = _load_template(template)
    rendered = raw_template.replace("{{ name }}", project_name)

    # Write config
    config_path.write_text(rendered)
    console.print(f"[green]Created[/green] {CONFIG_FILENAME}")

    # Create .nestdx/ directory
    _ensure_nestdx_dir(project_root)
    console.print("[green]Created[/green] .nestdx/sessions/")

    # Update .gitignore
    _update_gitignore(project_root)
    console.print("[green]Updated[/green] .gitignore")

    # Generate CI workflow if requested
    if ci:
        workflow_dir = project_root / ".github" / "workflows"
        workflow_dir.mkdir(parents=True, exist_ok=True)
        workflow_path = workflow_dir / "nestdx-audit.yaml"
        workflow_path.write_text(CI_WORKFLOW_TEMPLATE)
        console.print(f"[green]Created[/green] {workflow_path.relative_to(project_root)}")

    console.print(f"\n[bold]Workspace initialized:[/bold] {project_name}")
    console.print(f"  Template: {template}")
    console.print("\nNext: [cyan]nestdx start[/cyan] to begin a session.")
