#!/usr/bin/env -S uv run --script --no-project --isolated --refresh --quiet
# /// script
# requires-python = ">=3.13"
# dependencies = []
# ///

import sys, json, pathlib, subprocess

starting_paths = sys.argv[1:] or [pathlib.Path.home()]

fd_result = subprocess.run(
    ["fd", "--hidden", "--no-ignore", "--type", "d", "--type", "f", r"^\.git$", *starting_paths],
    capture_output=True,
    text=True,
    check=True,
)

home = pathlib.Path.home()
config_path = home / ".config/rgit/config.json"
config_path.parent.mkdir(parents=True, exist_ok=True)
config = json.loads(config_path.read_text()) if config_path.exists() else {}
repos = set(config.get("repositories", []))
for line in fd_result.stdout.splitlines():
    p = pathlib.Path(line.strip())
    try:
        p = p.relative_to(home)
    except ValueError:
        pass
    repos.add(p.as_posix())
config["repositories"] = sorted(repos)
config_path.write_text(json.dumps(config, indent="\t") + "\n")
print(len(config["repositories"]), "repositories total")
