import { randomUUID } from "node:crypto";
import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js";
import { archivePaseoWorktree } from "../paseo-worktree-archive-service.js";
export class CreateAgentLifecycleDispatch {
    constructor(dependencies) {
        this.dependencies = dependencies;
        this.autoArchiveAgentIds = new Set();
    }
    async createWorktreeForRequest(input) {
        if (input.target && input.hasLegacyGitOptions) {
            throw new Error("create_agent_request worktree cannot be combined with git options");
        }
        if (!input.target) {
            return null;
        }
        return this.createWorktreeForTarget(input.cwd, input.target, input.firstAgentContext);
    }
    registerAutoArchiveIfRequested(input) {
        if (input.autoArchive !== true) {
            return;
        }
        this.registerAutoArchiveOnTerminalState(input.agentId, {
            worktreePath: input.createdWorktree?.worktree.worktreePath ?? null,
            repoRoot: input.createdWorktree?.repoRoot ?? null,
        });
    }
    async cleanupCreatedWorktreeAfterFailedAgentCreate(input) {
        const { createdWorktree, createdAgentId } = input;
        if (!createdWorktree || createdAgentId) {
            return;
        }
        await this.archiveAutoCreatedWorktree({
            agentId: null,
            worktreePath: createdWorktree.worktree.worktreePath,
            repoRoot: createdWorktree.repoRoot,
        }).catch((archiveError) => {
            this.dependencies.logger.warn({
                err: archiveError,
                worktreePath: createdWorktree.worktree.worktreePath,
            }, "Failed to clean up worktree after create_agent_request failed");
        });
    }
    async createWorktreeForTarget(cwd, target, firstAgentContext) {
        const baseInput = {
            cwd,
            firstAgentContext,
            runSetup: false,
            paseoHome: this.dependencies.paseoHome,
            worktreesRoot: this.dependencies.worktreesRoot,
        };
        switch (target.mode) {
            case "branch-off":
                return this.dependencies.createPaseoWorktreeWorkflow({
                    ...baseInput,
                    worktreeSlug: target.newBranch,
                    action: "branch-off",
                    ...(target.base ? { refName: target.base } : {}),
                }, target.base ? { resolveDefaultBranch: async () => target.base } : undefined);
            case "checkout-branch":
                return this.dependencies.createPaseoWorktreeWorkflow({
                    ...baseInput,
                    action: "checkout",
                    refName: target.branch,
                });
            case "checkout-pr":
                return this.dependencies.createPaseoWorktreeWorkflow({
                    ...baseInput,
                    action: "checkout",
                    githubPrNumber: target.prNumber,
                });
            default:
                throw new Error("Unsupported create_agent_request worktree target");
        }
    }
    registerAutoArchiveOnTerminalState(agentId, options) {
        const unsubscribe = this.dependencies.agentManager.subscribe((event) => {
            if (event.type !== "agent_stream") {
                return;
            }
            if (event.event.type !== "turn_completed" &&
                event.event.type !== "turn_failed" &&
                event.event.type !== "turn_canceled") {
                return;
            }
            unsubscribe();
            void this.autoArchiveAgentOnce(agentId, options);
        }, { agentId, replayState: false });
    }
    async autoArchiveAgentOnce(agentId, options) {
        if (this.autoArchiveAgentIds.has(agentId)) {
            return;
        }
        this.autoArchiveAgentIds.add(agentId);
        try {
            if (options.worktreePath) {
                await this.archiveAutoCreatedWorktree({
                    agentId,
                    worktreePath: options.worktreePath,
                    repoRoot: options.repoRoot,
                });
                return;
            }
            await this.dependencies.archiveAgentForClose(agentId);
        }
        catch (error) {
            this.dependencies.logger.warn({ err: error, agentId }, "Failed to auto-archive agent");
        }
    }
    async archiveAutoCreatedWorktree(options) {
        const ownership = await isPaseoOwnedWorktreeCwd(options.worktreePath, {
            paseoHome: this.dependencies.paseoHome,
            worktreesRoot: this.dependencies.worktreesRoot,
        });
        if (!ownership.allowed) {
            throw new Error("Auto-created worktree is not a Paseo-owned worktree");
        }
        await archivePaseoWorktree({
            paseoHome: this.dependencies.paseoHome,
            worktreesRoot: this.dependencies.worktreesRoot,
            github: this.dependencies.github,
            workspaceGitService: this.dependencies.workspaceGitService,
            agentManager: this.dependencies.agentManager,
            agentStorage: this.dependencies.agentStorage,
            archiveWorkspaceRecord: this.dependencies.archiveWorkspaceRecord,
            emitWorkspaceUpdatesForWorkspaceIds: this.dependencies.emitWorkspaceUpdatesForWorkspaceIds,
            markWorkspaceArchiving: this.dependencies.markWorkspaceArchiving,
            clearWorkspaceArchiving: this.dependencies.clearWorkspaceArchiving,
            isPathWithinRoot: this.dependencies.isPathWithinRoot,
            killTerminalsUnderPath: this.dependencies.killTerminalsUnderPath,
            sessionLogger: this.dependencies.logger,
        }, {
            targetPath: options.worktreePath,
            repoRoot: options.repoRoot ?? ownership.repoRoot ?? null,
            worktreesRoot: ownership.worktreeRoot,
            worktreesBaseRoot: this.dependencies.worktreesRoot,
            requestId: randomUUID(),
        });
        if (options.agentId) {
            this.dependencies.emitAgentRemove(options.agentId);
        }
    }
}
//# sourceMappingURL=create-agent-lifecycle-dispatch.js.map