"""pjctx share — Remove .pjctx/ from .gitignore and commit it."""

from __future__ import annotations

from pathlib import Path

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


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

    if not get_pjctx_dir(repo_root).exists():
        ui.error("Not initialized. Run 'pjctx init' first.")
        raise SystemExit(1)

    if not ui.confirm("This will commit .pjctx/ to git for team sharing. Continue?"):
        ui.info("Cancelled.")
        return

    # Remove .pjctx/ from .gitignore
    _remove_from_gitignore(repo_root)

    # Git add and commit
    from git import Repo
    repo = Repo(repo_root)
    repo.index.add([".pjctx/"])
    repo.index.commit("chore: share .pjctx/ context with team")

    ui.success(".pjctx/ committed to git.")
    ui.info("Team members can now 'pjctx resume' after pulling.")


def _remove_from_gitignore(repo_root: Path) -> None:
    gitignore = repo_root / ".gitignore"
    if not gitignore.exists():
        return

    lines = gitignore.read_text().splitlines()
    new_lines = [l for l in lines if l.strip() != ".pjctx/" and l.strip() != "# PJContext local data"]
    gitignore.write_text("\n".join(new_lines) + "\n")
    ui.info("Removed .pjctx/ from .gitignore")
