import { defineHandler, useConfig } from '@kb-labs/sdk';
import { loadPlan } from '@kb-labs/commit-core/storage';
import { getGitStatus } from '@kb-labs/commit-core/analyzer';
import { COMMIT_CACHE_PREFIX, resolveCommitConfig } from '@kb-labs/commit-contracts';
import * as path from 'path';

// src/rest/handlers/status-handler.ts
function resolveScopePath(baseCwd, scopeId = "root", scopes) {
  const scopeDef = scopes?.find((s) => s.id === scopeId);
  const relativePath = scopeDef?.path ?? (scopeId === "root" ? "." : scopeId);
  return relativePath === "." ? baseCwd : path.join(baseCwd, relativePath);
}

// src/rest/handlers/status-handler.ts
var STATUS_CACHE_TTL = 5e3;
var status_handler_default = defineHandler({
  async execute(ctx, input) {
    const scope = input.query?.scope || "root";
    ctx.platform.logger.info(`[status-handler] Fetching status for scope: ${scope}`);
    try {
      const plan = await loadPlan(ctx.cwd, scope);
      ctx.platform.logger.info(`[status-handler] Plan loaded: ${!!plan}`);
      let filesChanged = 0;
      let gitStatus = null;
      const cacheKey = `${COMMIT_CACHE_PREFIX}git-status:${scope}`;
      ctx.platform.logger.info(`[status-handler] Cache key: ${cacheKey}`);
      const cached = await ctx.platform.cache.get(cacheKey);
      ctx.platform.logger.info(`[status-handler] Cache hit: ${!!cached}`);
      if (cached !== null && cached !== void 0) {
        const cachedData = cached;
        filesChanged = cachedData.count;
        gitStatus = cachedData.status;
      } else {
        const fileConfig = await useConfig();
        const config = resolveCommitConfig(fileConfig ?? {});
        const scopeCwd = resolveScopePath(ctx.cwd, scope, config.scope?.scopes);
        ctx.platform.logger.info(`[status-handler] Resolved scope CWD: ${scopeCwd}`);
        gitStatus = await getGitStatus(scopeCwd);
        ctx.platform.logger.info(`[status-handler] Git status fetched - staged: ${gitStatus.staged.length}, unstaged: ${gitStatus.unstaged.length}, untracked: ${gitStatus.untracked.length}`);
        filesChanged = gitStatus.staged.length + gitStatus.unstaged.length + gitStatus.untracked.length;
        ctx.platform.logger.info(`[status-handler] Total files changed: ${filesChanged}`);
        await ctx.platform.cache.set(
          cacheKey,
          { count: filesChanged, status: gitStatus },
          STATUS_CACHE_TTL
        );
      }
      let planStatus = "idle";
      let commitsApplied = 0;
      if (plan) {
        const appliedCacheKey = `${COMMIT_CACHE_PREFIX}plan-applied:${scope}`;
        const appliedData = await ctx.platform.cache.get(appliedCacheKey);
        if (appliedData) {
          const applied = appliedData;
          if (!applied.planCreatedAt || applied.planCreatedAt === plan.createdAt) {
            commitsApplied = applied.commitsApplied;
            planStatus = "applied";
          } else {
            await ctx.platform.cache.delete(appliedCacheKey);
            planStatus = "ready";
          }
        } else {
          planStatus = "ready";
        }
      }
      return {
        scope,
        hasPlan: !!plan,
        planStatus,
        filesChanged,
        commitsInPlan: plan?.commits.length || 0,
        commitsApplied,
        planTimestamp: plan?.createdAt,
        gitStatus: gitStatus || void 0
      };
    } catch (error) {
      return {
        scope,
        hasPlan: false,
        planStatus: "idle",
        filesChanged: 0,
        commitsInPlan: 0,
        commitsApplied: 0
      };
    }
  }
});

export { status_handler_default as default };
//# sourceMappingURL=status-handler.js.map
//# sourceMappingURL=status-handler.js.map