/**
 * Remove Command
 *
 * Removes a repository from Ghostflow synchronization.
 * Works without the daemon running by writing to config directly.
 * If the daemon is running, it will be notified to reload the configuration.
 */
import { Args, Command, Options } from "@effect/cli";
import { ConfigManager, GhostflowClient, isConfigStorageError, isFlowError, reloadWithVerification } from "@ghostflow/client";
import { decodeFlowId } from "@ghostflow/client/schemas";
import { Console, Data, Effect, pipe } from "effect";
import { ANSI, msg } from "../constants/ansi.js";
// ============================================================================
// Errors
// ============================================================================
class RemoveFlowError extends Data.TaggedError("RemoveFlowError") {
}
// ============================================================================
// Validation Helpers
// ============================================================================
/**
 * Validate and decode a flow ID string to the branded ConfigFlowId type.
 */
const validateFlowId = (rawId) => pipe(decodeFlowId(rawId), Effect.mapError(() => new RemoveFlowError({
    message: `Invalid flow ID format: ${rawId}\nExpected UUID (e.g., 550e8400-e29b-41d4-a716-446655440000)`
})));
// ============================================================================
// Daemon Reload Helper
// ============================================================================
/**
 * Try to reload the daemon if it's running with verification.
 * Returns verification result or undefined if daemon isn't running.
 */
const tryReloadDaemon = () => pipe(Effect.gen(function* () {
    const client = yield* GhostflowClient;
    return yield* reloadWithVerification(client);
}), Effect.catchAll(() => Effect.succeed(undefined)));
// ============================================================================
// Arguments & Options
// ============================================================================
const flowIdArg = Args.text({ name: "flow-id" }).pipe(Args.withDescription("Flow ID (UUID) to remove"));
const forceOption = Options.boolean("force").pipe(Options.withAlias("f"), Options.withDescription("Skip confirmation prompt"), Options.withDefault(false));
// ============================================================================
// Command Implementation
// ============================================================================
const removeHandler = ({ flowId: rawFlowId, force }) => pipe(Effect.gen(function* () {
    // Validate and decode flow ID
    const flowId = yield* validateFlowId(rawFlowId);
    yield* Console.log(`Removing flow ${flowId}...`);
    if (!force) {
        yield* Console.log(`${ANSI.YELLOW}Note:${ANSI.RESET} This will stop syncing the repository.`);
    }
    // Remove flow via ConfigManager (writes to config directly)
    const configManager = yield* ConfigManager;
    yield* configManager.removeFlow(flowId);
    yield* Console.log(`${ANSI.GREEN}✓${ANSI.RESET} Flow removed successfully`);
    // Try to reload daemon with verification (graceful if not running)
    const reloadResult = yield* tryReloadDaemon();
    if (reloadResult !== undefined) {
        const { reloadData } = reloadResult;
        yield* Console.log(`  ${msg.dim(`Daemon reloaded (${reloadData.flowCount} flows active)`)}`);
        if (reloadData.removedFlows.length > 0) {
            yield* Console.log(`  ${msg.dim(`Removed flows: ${reloadData.removedFlows.join(", ")}`)}`);
        }
    }
}), Effect.catchAll((error) => Effect.gen(function* () {
    // Handle config storage errors
    if (isConfigStorageError(error)) {
        yield* Console.error(msg.error(`Failed to write configuration: ${error.message}`));
        return yield* Effect.fail(error);
    }
    // Handle flow-specific errors with helpful messages
    if (isFlowError(error)) {
        yield* Console.error(msg.error(`Flow not found: ${rawFlowId}`));
        yield* Console.error("Use 'ghostflow list' to see existing flows.");
        return yield* Effect.fail(error);
    }
    // Handle RemoveFlowError from validation
    if (error instanceof RemoveFlowError) {
        yield* Console.error(msg.error(error.message));
        return yield* Effect.fail(error);
    }
    // Generic error
    yield* Console.error(msg.error(String(error)));
    return yield* Effect.fail(error);
})));
// ============================================================================
// Command Definition
// ============================================================================
export const removeCommand = Command.make("remove", {
    flowId: flowIdArg,
    force: forceOption
}).pipe(Command.withHandler(removeHandler), Command.withDescription("Remove a repository from sync"));
//# sourceMappingURL=remove.js.map