/**
 * Stop Command
 *
 * Stops the Ghostflow daemon via launchd.
 */
import { Command } from "@effect/cli";
import { LaunchdService } from "@ghostflow/client";
import { Console, Data, Effect, Match, pipe } from "effect";
import { msg } from "../constants/ansi.js";
// ============================================================================
// Errors
// ============================================================================
class StopError extends Data.TaggedError("StopError") {
}
// ============================================================================
// Command Implementation
// ============================================================================
const stopHandler = () => pipe(Effect.gen(function* () {
    const launchd = yield* LaunchdService;
    const status = yield* launchd.status();
    // Handle different daemon states using Match pattern
    yield* pipe(Match.value({ isLoaded: status.isLoaded, isRunning: status.isRunning }), Match.when({ isLoaded: false }, () => Console.log(msg.warning("Ghostflow daemon is not loaded"))), Match.when({ isRunning: false }, () => Effect.gen(function* () {
        yield* Console.log(msg.warning("Ghostflow daemon is not running"));
        yield* launchd.unload();
        yield* Console.log("  Unloaded from launchd");
    })), Match.orElse(() => Effect.gen(function* () {
        yield* Console.log(`Stopping Ghostflow daemon (PID: ${status.pid})...`);
        yield* launchd.unload();
        yield* Effect.sleep("500 millis");
        const newStatus = yield* launchd.status();
        yield* Effect.if(!newStatus.isRunning, {
            onTrue: () => Console.log(msg.running("Ghostflow daemon stopped")),
            onFalse: () => Effect.gen(function* () {
                yield* Console.error(msg.stopped("Failed to stop daemon"));
                yield* Effect.fail(new StopError({ message: "Failed to stop daemon" }));
            })
        });
    })));
}), Effect.catchAll((error) => Effect.gen(function* () {
    yield* Console.error(msg.error(String(error)));
    return yield* Effect.fail(error);
})));
// ============================================================================
// Command Definition
// ============================================================================
export const stopCommand = Command.make("stop", {}).pipe(Command.withHandler(stopHandler), Command.withDescription("Stop the Ghostflow daemon"));
//# sourceMappingURL=stop.js.map