/**
 * Git Worktree Service Implementation
 *
 * Manages git worktrees using native execFile for process execution.
 * Uses constructor dependency injection for the command executor
 * to enable testability without mocking node:child_process directly.
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { createHash } from 'node:crypto';
import { mkdirSync, realpathSync } from 'node:fs';
import path from 'node:path';
import { injectable, inject } from 'tsyringe';
const GIT_AUTO_INIT_USER = 'shep-ai[bot]';
const GIT_AUTO_INIT_EMAIL = 'bot@shep.bot';
import { WorktreeError, WorktreeErrorCode, } from '../../../application/ports/output/services/worktree-service.interface.js';
import { getShepHomeDir } from '../filesystem/shep-directory.service.js';
import { IS_WINDOWS } from '../../platform.js';
let WorktreeService = class WorktreeService {
    execFile;
    constructor(execFile) {
        this.execFile = execFile;
    }
    async create(repoPath, branch, worktreePath, startPoint) {
        try {
            const args = ['worktree', 'add', worktreePath, '-b', branch];
            if (startPoint)
                args.push(startPoint);
            await this.execFile('git', args, { cwd: repoPath });
        }
        catch (error) {
            throw this.parseGitError(error);
        }
        // Get info about the created worktree — match by branch (reliable) then path
        const worktrees = await this.list(repoPath);
        const created = worktrees.find((w) => w.branch === branch) ??
            worktrees.find((w) => this.arePathsEquivalent(w.path, worktreePath));
        if (!created) {
            throw new WorktreeError('Worktree created but not found in list', WorktreeErrorCode.GIT_ERROR);
        }
        return created;
    }
    async addExisting(repoPath, branch, worktreePath) {
        try {
            await this.execFile('git', ['worktree', 'add', worktreePath, branch], { cwd: repoPath });
        }
        catch (error) {
            throw this.parseGitError(error);
        }
        const worktrees = await this.list(repoPath);
        const created = worktrees.find((w) => w.branch === branch) ??
            worktrees.find((w) => this.arePathsEquivalent(w.path, worktreePath));
        if (!created) {
            throw new WorktreeError('Worktree created but not found in list', WorktreeErrorCode.GIT_ERROR);
        }
        return created;
    }
    async remove(repoPath, worktreePath, force) {
        try {
            const args = ['worktree', 'remove'];
            if (force)
                args.push('--force');
            args.push(worktreePath);
            await this.execFile('git', args, { cwd: repoPath });
        }
        catch (error) {
            throw this.parseGitError(error);
        }
    }
    async prune(repoPath) {
        try {
            await this.execFile('git', ['worktree', 'prune'], { cwd: repoPath });
        }
        catch (error) {
            throw this.parseGitError(error);
        }
    }
    async list(repoPath) {
        const { stdout } = await this.execFile('git', ['worktree', 'list', '--porcelain'], {
            cwd: repoPath,
        });
        return this.parseWorktreeOutput(stdout);
    }
    async exists(repoPath, branch) {
        const worktrees = await this.list(repoPath);
        return worktrees.some((w) => w.branch === branch);
    }
    async branchExists(repoPath, branch) {
        try {
            const { stdout } = await this.execFile('git', ['branch', '--list', branch], {
                cwd: repoPath,
            });
            return stdout.trim().length > 0;
        }
        catch {
            return false;
        }
    }
    async remoteBranchExists(repoPath, branch) {
        try {
            const { stdout } = await this.execFile('git', ['ls-remote', '--heads', 'origin', branch], {
                cwd: repoPath,
            });
            return stdout.trim().length > 0;
        }
        catch {
            return false;
        }
    }
    async listBranches(repoPath) {
        try {
            const { stdout } = await this.execFile('git', ['branch', '-a', '--format=%(refname:short)'], {
                cwd: repoPath,
            });
            const seen = new Set();
            const branches = [];
            for (const line of stdout.split('\n')) {
                const trimmed = line.trim();
                if (!trimmed || trimmed === 'origin/HEAD' || trimmed.startsWith('origin/HEAD ->'))
                    continue;
                // Strip "origin/" prefix for remote branches
                const name = trimmed.startsWith('origin/') ? trimmed.slice('origin/'.length) : trimmed;
                if (!seen.has(name)) {
                    seen.add(name);
                    branches.push(name);
                }
            }
            return branches.sort();
        }
        catch {
            return [];
        }
    }
    async ensureGitRepository(repoPath) {
        let isExistingRepo = false;
        try {
            await this.execFile('git', ['rev-parse', '--is-inside-work-tree'], { cwd: repoPath });
            isExistingRepo = true;
        }
        catch {
            // Not a git repo — will initialize below
        }
        if (isExistingRepo) {
            // Repo exists but may have an unborn branch (no commits).
            // git worktree add requires at least one commit as a start-point.
            try {
                await this.execFile('git', ['rev-parse', 'HEAD'], { cwd: repoPath });
                return; // Has commits — nothing to do
            }
            catch {
                // Unborn branch (no commits) — create initial commit below
            }
        }
        try {
            if (!isExistingRepo) {
                mkdirSync(repoPath, { recursive: true });
                await this.execFile('git', ['init', '-b', 'main'], { cwd: repoPath });
            }
            await this.execFile('git', ['config', 'user.name', GIT_AUTO_INIT_USER], { cwd: repoPath });
            await this.execFile('git', ['config', 'user.email', GIT_AUTO_INIT_EMAIL], { cwd: repoPath });
            // Stage any existing files so they appear in the worktree after creation.
            // --allow-empty ensures the commit succeeds even if the directory is empty.
            await this.execFile('git', ['add', '.'], { cwd: repoPath });
            await this.execFile('git', ['commit', '--allow-empty', '--no-gpg-sign', '-m', 'Initial commit'], { cwd: repoPath });
        }
        catch (error) {
            throw this.parseGitError(error);
        }
    }
    getWorktreePath(repoPath, branch) {
        // Normalize separators before hashing so C:\foo and C:/foo produce the same hash
        const normalizedRepoPath = repoPath.replace(/\\/g, '/');
        const repoHash = createHash('sha256').update(normalizedRepoPath).digest('hex').slice(0, 16);
        const slug = branch.replace(/\//g, '-');
        return path.join(getShepHomeDir(), 'repos', repoHash, 'wt', slug).replace(/\\/g, '/');
    }
    parseWorktreeOutput(output) {
        if (!output.trim())
            return [];
        const worktrees = [];
        const blocks = output.split('\n\n').filter((b) => b.trim());
        for (const block of blocks) {
            const lines = block.split('\n');
            const wtPath = lines.find((l) => l.startsWith('worktree '))?.slice('worktree '.length) ?? '';
            const head = lines.find((l) => l.startsWith('HEAD '))?.slice('HEAD '.length) ?? '';
            const branchLine = lines.find((l) => l.startsWith('branch '));
            const fullBranch = branchLine?.slice('branch '.length) ?? '';
            const branch = fullBranch.replace('refs/heads/', '');
            if (wtPath) {
                worktrees.push({
                    path: wtPath,
                    head,
                    branch,
                    isMain: worktrees.length === 0, // First entry is always main
                });
            }
        }
        return worktrees;
    }
    parseGitError(error) {
        const message = error instanceof Error ? error.message : String(error);
        if (message.includes('already exists')) {
            return new WorktreeError(message, WorktreeErrorCode.ALREADY_EXISTS, error instanceof Error ? error : undefined);
        }
        if (message.includes('already checked out') || message.includes('is already checked out')) {
            return new WorktreeError(message, WorktreeErrorCode.BRANCH_IN_USE, error instanceof Error ? error : undefined);
        }
        if (message.includes('not a valid directory') || message.includes('is not a working tree')) {
            return new WorktreeError(message, WorktreeErrorCode.NOT_FOUND, error instanceof Error ? error : undefined);
        }
        return new WorktreeError(message, WorktreeErrorCode.GIT_ERROR, error instanceof Error ? error : undefined);
    }
    arePathsEquivalent(a, b) {
        return this.normalizeWorktreePath(a) === this.normalizeWorktreePath(b);
    }
    normalizeWorktreePath(input) {
        // On Windows, git outputs forward slashes but path.normalize uses backslashes.
        // Normalize to forward slashes before comparing, case-insensitive.
        if (IS_WINDOWS) {
            let normalized = path.normalize(input).replace(/\\/g, '/').replace(/\/+$/, '');
            try {
                normalized = realpathSync(normalized).replace(/\\/g, '/');
            }
            catch {
                // Path may not exist yet — use as-is
            }
            return normalized.toLowerCase();
        }
        const normalized = path.normalize(input).replace(/\/+$/, '');
        // On macOS, git can report /private/var/... while callers use /var/...
        if (process.platform === 'darwin' && normalized.startsWith('/private/var/')) {
            return normalized.slice('/private'.length);
        }
        return normalized;
    }
};
WorktreeService = __decorate([
    injectable(),
    __param(0, inject('ExecFunction')),
    __metadata("design:paramtypes", [Function])
], WorktreeService);
export { WorktreeService };
