/**
 * identity.mjs — git user/branch auto-detection helpers (C29).
 */

import { execSync } from 'node:child_process'

/**
 * Auto-detect the current user's git identity. Returns null if git config is unset.
 */
export function getGitIdentity(targetDir) {
	try {
		const name = execSync('git config user.name 2>/dev/null', {
			cwd: targetDir,
			encoding: 'utf-8',
		}).trim()
		const email = execSync('git config user.email 2>/dev/null', {
			cwd: targetDir,
			encoding: 'utf-8',
		}).trim()
		if (!name || !email) return null
		return { name, email }
	} catch {
		return null
	}
}

/**
 * Default owner string for roadmap phases when `--owner` is not passed.
 * Uses the current user's git identity name so solo developers are attributed
 * automatically. Team-mode skills can override by passing `--owner` explicitly
 * (typically after prompting against team.json members).
 */
export function getDefaultOwner(targetDir) {
	const identity = getGitIdentity(targetDir)
	return identity?.name || 'TBD'
}

/**
 * Auto-detect the current git branch. Returns null if not in a git repo or detached HEAD.
 */
export function getCurrentBranch(targetDir) {
	try {
		const branch = execSync('git rev-parse --abbrev-ref HEAD 2>/dev/null', {
			cwd: targetDir,
			encoding: 'utf-8',
		}).trim()
		if (!branch || branch === 'HEAD') return null
		return branch
	} catch {
		return null
	}
}
