import {
  createWUParser,
  runCLI,
  withMicroWorktree
} from "./chunk-2GXVIN57.js";
import {
  EXIT_CODES,
  LUMENFLOW_PATHS
} from "./chunk-DWMLTXKQ.js";

// src/state-emit.ts
import fs from "fs/promises";
import path from "path";
var VALID_EMIT_TYPES = ["claim", "release", "complete"];
var WU_ID_PATTERN = /^WU-\d+$/;
var LOG_PREFIX = "[state:emit]";
var TOOL_NAME = "state:emit";
function validateParams(opts) {
  if (!VALID_EMIT_TYPES.includes(opts.type)) {
    throw new Error(
      `Invalid event type: '${opts.type}'. Valid types: ${VALID_EMIT_TYPES.join(", ")}`
    );
  }
  if (!opts.reason || opts.reason.trim().length === 0) {
    throw new Error("Reason is required for corrective events");
  }
  if (!WU_ID_PATTERN.test(opts.wuId)) {
    throw new Error(`Invalid WU ID: '${opts.wuId}'. Must match pattern WU-XXX (e.g., WU-123)`);
  }
}
function getTransactionalCommitMessage(type, wuId) {
  return `chore(repair): emit corrective ${type} event for ${wuId.toLowerCase()}`;
}
async function emitCorrectiveEvent(opts) {
  validateParams(opts);
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
  const event = {
    wuId: opts.wuId,
    type: opts.type,
    reason: opts.reason,
    timestamp,
    source: TOOL_NAME,
    corrective: true
  };
  if (opts.type === "claim") {
    if (opts.lane) event.lane = opts.lane;
    if (opts.title) event.title = opts.title;
  }
  const eventLine = JSON.stringify(event);
  await fs.mkdir(path.dirname(opts.eventsFilePath), { recursive: true });
  await fs.appendFile(opts.eventsFilePath, eventLine + "\n", "utf-8");
  await writeAuditLog(opts.auditLogPath, {
    tool: TOOL_NAME,
    status: "success",
    timestamp,
    input: {
      type: opts.type,
      wuId: opts.wuId,
      reason: opts.reason
    }
  });
}
async function emitCorrectiveEventTransactionally(opts, deps = {}) {
  validateParams(opts);
  const withMicroWorktreeImpl = deps.withMicroWorktreeImpl ?? withMicroWorktree;
  const emitCorrectiveEventImpl = deps.emitCorrectiveEventImpl ?? emitCorrectiveEvent;
  await withMicroWorktreeImpl({
    operation: "state-emit",
    id: `emit-${opts.wuId.toLowerCase()}-${opts.type}`,
    logPrefix: LOG_PREFIX,
    pushOnly: true,
    execute: async ({ worktreePath }) => {
      const eventsFilePath = path.join(worktreePath, LUMENFLOW_PATHS.WU_EVENTS);
      const auditLogPath = path.join(worktreePath, LUMENFLOW_PATHS.AUDIT_LOG);
      await emitCorrectiveEventImpl({
        type: opts.type,
        wuId: opts.wuId,
        reason: opts.reason,
        eventsFilePath,
        auditLogPath,
        lane: opts.lane,
        title: opts.title
      });
      return {
        commitMessage: getTransactionalCommitMessage(opts.type, opts.wuId),
        files: [LUMENFLOW_PATHS.WU_EVENTS]
      };
    }
  });
}
async function writeAuditLog(logPath, entry) {
  try {
    await fs.mkdir(path.dirname(logPath), { recursive: true });
    await fs.appendFile(logPath, JSON.stringify(entry) + "\n", "utf-8");
  } catch {
  }
}
function parseArguments() {
  return createWUParser({
    name: "state-emit",
    description: "Emit a corrective event to the state store",
    options: [
      {
        name: "type",
        flags: "-t, --type <type>",
        description: `Event type (${VALID_EMIT_TYPES.join(", ")})`
      },
      {
        name: "wu",
        flags: "--wu <wuId>",
        description: "Work Unit ID (e.g., WU-123)"
      },
      {
        name: "reason",
        flags: "-r, --reason <reason>",
        description: "Reason for the corrective event (required)"
      },
      {
        name: "baseDir",
        flags: "-b, --base-dir <path>",
        description: "Base directory (defaults to current directory)"
      },
      {
        name: "transactional",
        flags: "--transactional",
        description: "Commit corrective event via micro-worktree (push-only mode)"
      }
    ],
    required: [],
    allowPositionalId: false
  });
}
async function main() {
  const args = parseArguments();
  if (!args.type) {
    console.error(`${LOG_PREFIX} Error: --type is required (${VALID_EMIT_TYPES.join(", ")})`);
    process.exit(EXIT_CODES.ERROR);
  }
  if (!args.wu) {
    console.error(`${LOG_PREFIX} Error: --wu is required (e.g., WU-123)`);
    process.exit(EXIT_CODES.ERROR);
  }
  if (!args.reason) {
    console.error(`${LOG_PREFIX} Error: --reason is required`);
    process.exit(EXIT_CODES.ERROR);
  }
  const baseDir = args.baseDir || process.cwd();
  const eventsFilePath = path.join(baseDir, LUMENFLOW_PATHS.WU_EVENTS);
  const auditLogPath = path.join(baseDir, LUMENFLOW_PATHS.AUDIT_LOG);
  try {
    if (args.transactional) {
      const resolvedBaseDir = path.resolve(baseDir);
      const resolvedCwd = path.resolve(process.cwd());
      if (resolvedBaseDir !== resolvedCwd) {
        throw new Error(
          "Transactional mode requires running from target repo root; --base-dir is not supported"
        );
      }
      await emitCorrectiveEventTransactionally({
        type: args.type,
        wuId: args.wu,
        reason: args.reason
      });
      console.log(`${LOG_PREFIX} Emitted corrective '${args.type}' event for ${args.wu}`);
      console.log(`${LOG_PREFIX} Mode: transactional (micro-worktree push-only)`);
      console.log(`${LOG_PREFIX} Reason: ${args.reason}`);
    } else {
      await emitCorrectiveEvent({
        type: args.type,
        wuId: args.wu,
        reason: args.reason,
        eventsFilePath,
        auditLogPath
      });
      console.log(`${LOG_PREFIX} Emitted corrective '${args.type}' event for ${args.wu}`);
      console.log(`${LOG_PREFIX} Mode: append-only`);
      console.log(`${LOG_PREFIX} Reason: ${args.reason}`);
      console.log(`${LOG_PREFIX} Events file: ${eventsFilePath}`);
    }
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    console.error(`${LOG_PREFIX} Error: ${message}`);
    process.exit(EXIT_CODES.ERROR);
  }
}
if (import.meta.main) {
  void runCLI(main);
}

export {
  VALID_EMIT_TYPES,
  emitCorrectiveEvent,
  emitCorrectiveEventTransactionally,
  main
};
