"""pjctx init — Create .pjctx/ structure and update .gitignore."""

from __future__ import annotations

from pathlib import Path

from pjctx.core.config import find_repo_root, get_pjctx_dir, save_config, DEFAULT_CONFIG
from pjctx import ui


def run_init(obj: dict) -> None:
    repo_root = find_repo_root()
    if repo_root is None:
        ui.error("Not inside a git repository. Run 'git init' first.")
        raise SystemExit(1)

    pjctx_dir = get_pjctx_dir(repo_root)

    if pjctx_dir.exists():
        ui.warning(".pjctx/ already exists. Skipping initialization.")
        return

    # Create directory structure
    (pjctx_dir / "contexts").mkdir(parents=True, exist_ok=True)
    (pjctx_dir / "hooks").mkdir(parents=True, exist_ok=True)

    # Write default config
    save_config(repo_root, DEFAULT_CONFIG)

    # Update .gitignore
    _update_gitignore(repo_root)

    ui.success(f"Initialized .pjctx/ in {repo_root}")
    ui.info("Run 'pjctx save' to capture your first context.")


def _update_gitignore(repo_root: Path) -> None:
    """Add .pjctx/ to .gitignore if not already present."""
    gitignore = repo_root / ".gitignore"
    marker = ".pjctx/"

    if gitignore.exists():
        content = gitignore.read_text()
        if marker in content.splitlines():
            return
        if not content.endswith("\n"):
            content += "\n"
    else:
        content = ""

    content += f"\n# PJContext local data\n{marker}\n"
    gitignore.write_text(content)
    ui.info("Added .pjctx/ to .gitignore")
