/**
 * 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 path from 'node:path';
import { injectable, inject } from 'tsyringe';
import { WorktreeError, WorktreeErrorCode, } from '../../../application/ports/output/services/worktree-service.interface.js';
import { SHEP_HOME_DIR } from '../filesystem/shep-directory.service.js';
let WorktreeService = class WorktreeService {
    execFile;
    constructor(execFile) {
        this.execFile = execFile;
    }
    async create(repoPath, branch, worktreePath) {
        try {
            await this.execFile('git', ['worktree', 'add', worktreePath, '-b', branch], {
                cwd: repoPath,
            });
        }
        catch (error) {
            throw this.parseGitError(error);
        }
        // Get info about the created worktree
        const worktrees = await this.list(repoPath);
        const created = worktrees.find((w) => w.path === worktreePath);
        if (!created) {
            throw new WorktreeError('Worktree created but not found in list', WorktreeErrorCode.GIT_ERROR);
        }
        return created;
    }
    async remove(worktreePath) {
        try {
            await this.execFile('git', ['worktree', 'remove', worktreePath], {});
        }
        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);
    }
    getWorktreePath(repoPath, branch) {
        const repoHash = createHash('sha256').update(repoPath).digest('hex').slice(0, 16);
        const slug = branch.replace(/\//g, '-');
        return path.join(SHEP_HOME_DIR, 'repos', repoHash, 'wt', slug);
    }
    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);
    }
};
WorktreeService = __decorate([
    injectable(),
    __param(0, inject('ExecFunction')),
    __metadata("design:paramtypes", [Function])
], WorktreeService);
export { WorktreeService };
