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

// src/rest/handlers/push-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/push-handler.ts
var push_handler_default = defineHandler({
  async execute(ctx, input) {
    const { scope = "root", remote, force } = input.body ?? {};
    const startTime = Date.now();
    try {
      const plan = await loadPlan(ctx.cwd, scope);
      const fileConfig = await useConfig();
      const config = resolveCommitConfig(fileConfig ?? {});
      const scopeCwd = resolveScopePath(ctx.cwd, scope, config.scope?.scopes);
      const result = await pushCommits(scopeCwd, { remote, force, scope });
      if (result.success && plan) {
        await saveToHistory(ctx.cwd, plan, {
          success: true,
          appliedCommits: [],
          errors: []
        }, scope);
        await clearPlan(ctx.cwd, scope);
        const appliedCacheKey = `${COMMIT_CACHE_PREFIX}plan-applied:${scope}`;
        await ctx.platform.cache.delete(appliedCacheKey);
      }
      if (ctx.platform.analytics) {
        if (result.success) {
          await ctx.platform.analytics.track("commit.push.success", {
            scope,
            remote,
            force,
            commitsPushed: plan?.commits.length || 0,
            durationMs: Date.now() - startTime
          });
        } else {
          await ctx.platform.analytics.track("commit.push.failed", {
            scope,
            remote,
            force,
            error: result.error,
            durationMs: Date.now() - startTime
          });
        }
      }
      return {
        result,
        scope
      };
    } catch (error) {
      if (ctx.platform.analytics) {
        await ctx.platform.analytics.track("commit.push.error", {
          scope,
          remote,
          force,
          error: error instanceof Error ? error.message : String(error),
          durationMs: Date.now() - startTime
        });
      }
      throw new Error(`Failed to push commits: ${error}`);
    }
  }
});

export { push_handler_default as default };
//# sourceMappingURL=push-handler.js.map
//# sourceMappingURL=push-handler.js.map