/**
 * DaemonPidService
 *
 * Infrastructure service for managing the daemon state file (~/.shep/daemon.json).
 * Implements IDaemonService output port.
 *
 * Uses atomic write (write-to-temp + rename) to prevent partial-write corruption.
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { readFile, writeFile, unlink, rename } from 'node:fs/promises';
import { injectable } from 'tsyringe';
import { getDaemonStatePath } from '../filesystem/shep-directory.service.js';
let DaemonPidService = class DaemonPidService {
    async read() {
        const filePath = getDaemonStatePath();
        try {
            const raw = await readFile(filePath, 'utf-8');
            return JSON.parse(raw);
        }
        catch (err) {
            if (isEnoent(err))
                return null;
            throw err;
        }
    }
    async write(data) {
        const finalPath = getDaemonStatePath();
        const tmpPath = `${finalPath}.tmp`;
        await writeFile(tmpPath, JSON.stringify(data), 'utf-8');
        await rename(tmpPath, finalPath);
    }
    async delete() {
        const filePath = getDaemonStatePath();
        try {
            await unlink(filePath);
        }
        catch (err) {
            if (isEnoent(err))
                return;
            throw err;
        }
    }
    isAlive(pid) {
        if (!isValidPid(pid))
            return false;
        try {
            process.kill(pid, 0);
            return true;
        }
        catch {
            return false;
        }
    }
};
DaemonPidService = __decorate([
    injectable()
], DaemonPidService);
export { DaemonPidService };
function isEnoent(err) {
    return (typeof err === 'object' &&
        err !== null &&
        'code' in err &&
        err.code === 'ENOENT');
}
function isValidPid(pid) {
    return Number.isFinite(pid) && Number.isInteger(pid) && pid > 0;
}
