export class AttachService {
    state;
    projectPath;
    constructor(state, projectPath) {
        this.state = state;
        this.projectPath = projectPath;
    }
    listUnfinished(limit = 20) {
        return this.state.listUnfinishedRuns(this.projectPath, limit);
    }
    latestUnfinished() {
        return this.listUnfinished(1)[0];
    }
    current() {
        const runId = this.state.getUiState(this.scope, "attached_run_id");
        if (!runId)
            return {};
        return {
            runId,
            run: this.state.getRun(runId),
        };
    }
    attach(runId) {
        const run = this.state.getRun(runId);
        if (!run)
            throw new Error(`run not found: ${runId}`);
        this.state.setUiState(this.scope, "attached_run_id", runId);
        this.state.appendEvent(runId, "run_attached", {
            project_path: this.projectPath,
        });
        return run;
    }
    attachLatest() {
        const run = this.latestUnfinished();
        if (!run)
            throw new Error("no unfinished run for this project");
        return this.attach(run.id);
    }
    clear() {
        const current = this.current();
        this.state.deleteUiState(this.scope, "attached_run_id");
        if (current.runId) {
            this.state.appendEvent(current.runId, "run_detached", {
                project_path: this.projectPath,
            });
        }
    }
    get scope() {
        return `tui:${this.projectPath}`;
    }
}
