import type { ProjectExecutionDecision } from "@qjclaw/shared-types";
import type { ProjectContextService } from "./project-context.js";
import type { ProjectStoreService } from "./project-store.js";

interface ProjectContextRefreshOptions {
  sessionId: string;
  projectId: string;
  projectContextService: ProjectContextService;
  projectStore: ProjectStoreService;
}

export function shouldRefreshProjectContextAfterExecution(decision: ProjectExecutionDecision): boolean {
  switch (decision.kind) {
    case "chat-fallback":
    case "skill":
    case "workspace-entry":
      return true;
    default: {
      const exhaustiveCheck: never = decision;
      throw new Error(`Unhandled project execution decision: ${JSON.stringify(exhaustiveCheck)}`);
    }
  }
}

export async function refreshProjectContextAfterExecution({
  sessionId,
  projectId,
  projectContextService,
  projectStore
}: ProjectContextRefreshOptions): Promise<void> {
  projectContextService.invalidateSnapshot(projectId);
  try {
    const snapshot = await projectContextService.refreshSnapshot(projectId);
    const latestSessionState = await projectStore.getSessionState(sessionId);
    if (latestSessionState.contextSnapshotId !== snapshot.snapshotId) {
      await projectStore.bindSessionContextSnapshot(sessionId, snapshot.snapshotId);
    }
  } catch {
    projectContextService.invalidateSnapshot(projectId);
  }
}
