#!/usr/bin/env nu
# reflection/bin/init-repo.nu — VCS-aware repository initialization.
#
# Called by the new_project mode init_repo step.
# Detects existing VCS state and initializes accordingly:
#   jj detected → jj git init --colocate (jj-native with git interop)
#   git detected → commit initial empty commit if needed
#   none detected → default to jj colocated (preferred for Radicle)
#
# Usage: nu reflection/bin/init-repo.nu <project_dir>

def main [project_dir: path]: nothing -> nothing {
    let dir = ($project_dir | path expand)

    if not ($dir | path exists) {
        mkdir $dir
    }

    let has_jj  = ($dir | path join ".jj"  | path exists)
    let has_git = ($dir | path join ".git" | path exists)

    if $has_jj {
        # Already a jj repo — nothing to do
        print $"  ($dir) already a jj repo"
        return
    }

    if $has_git {
        # Existing git repo — ensure at least one commit exists for worktree ops
        let log = do { ^git -C $dir log --oneline -1 } | complete
        if $log.exit_code != 0 or ($log.stdout | str trim | is-empty) {
            std fs write-all $"($dir)/README" ""
            do { ^git -C $dir add README } | complete | ignore
            do { ^git -C $dir commit --allow-empty -m "chore: initial commit" } | complete | ignore
        }
        print $"  ($dir) git repo ready"
        return
    }

    # No VCS — initialize jj colocated (creates both .jj/ and .git/)
    let r = do { ^jj git init --colocate $dir } | complete
    if $r.exit_code != 0 {
        error make { msg: $"init-repo: jj git init failed: ($r.stderr)" }
    }

    print $"  ($dir) initialized as jj colocated repo"
}
