import fsp from 'node:fs/promises';
import path from 'node:path';
import { ensureDir, nowIso, packageRoot, readText, sha256, writeJsonAtomic, writeTextAtomic } from '../../fsx.js';
import { createMadSksAuditLedger, madSksAuditAction, writeMadSksAuditLedger } from '../audit-ledger.js';
import {} from '../authorization-manifest.js';
import { compareProtectedCoreSnapshots, snapshotProtectedCore } from '../immutable-harness-guard.js';
import {} from '../permission-model.js';
import { createMadSksProofEvidence, writeMadSksProofEvidence } from '../proof-evidence.js';
import { createMadSksRollbackPlan, writeMadSksRollbackPlan } from '../rollback-plan.js';
import { redactMadSksSecrets } from '../write-guard.js';
export const MAD_SKS_EXECUTOR_INPUT_SCHEMA = 'sks.mad-sks-executor-input.v1';
export const MAD_SKS_EXECUTOR_RESULT_SCHEMA = 'sks.mad-sks-executor-result.v1';
export function createMadSksExecutorContext(input) {
    const targetRoot = path.resolve(String(input.target_root || input.permission_model?.target_root || process.cwd()));
    return {
        target_root: targetRoot,
        package_root: packageRoot(),
        artifact_dir: path.resolve(String(input.artifact_dir || path.join(targetRoot, '.sneakoscope', 'mad-sks-artifacts'))),
        authorization_manifest: input.authorization_manifest || null,
        authorization_manifest_path: input.authorization_manifest_path || null,
        permission_model: input.permission_model,
        local_only_artifact_policy: true
    };
}
export function executorBlocker({ executor, actionType, context, blockers, blockedActions = [] }) {
    return {
        schema: MAD_SKS_EXECUTOR_RESULT_SCHEMA,
        ok: false,
        status: 'blocked',
        executor,
        action_type: actionType,
        target_root: context.target_root,
        changed_files: [],
        audit_ledger_path: null,
        rollback_plan_path: null,
        proof_evidence_path: null,
        verification: [],
        blocked_actions: blockedActions,
        blockers,
        writes_performed: false,
        local_only_artifact_policy: true,
        generated_at: nowIso()
    };
}
export async function writeExecutorEvidence({ context, executor, actionType, changedFiles = [], blockedActions = [], fileRollbacks = [], packageRollbacks = [], serviceRollbacks = [], dbRollbacks = [], rollbackUnavailable = [], auditActions = [], verification = [] }) {
    await ensureDir(context.artifact_dir);
    const before = await snapshotProtectedCore(context.package_root, `${executor}-before`);
    const after = await snapshotProtectedCore(context.package_root, `${executor}-after`);
    const comparison = compareProtectedCoreSnapshots(before, after);
    const beforePath = path.join(context.artifact_dir, `${executor}-protected-core-before.json`);
    const afterPath = path.join(context.artifact_dir, `${executor}-protected-core-after.json`);
    const comparisonPath = path.join(context.artifact_dir, `${executor}-protected-core-comparison.json`);
    const auditPath = path.join(context.artifact_dir, `${executor}-audit-ledger.json`);
    const rollbackPath = path.join(context.artifact_dir, `${executor}-rollback-plan.json`);
    const proofPath = path.join(context.artifact_dir, `${executor}-proof-evidence.json`);
    await writeJsonAtomic(beforePath, before);
    await writeJsonAtomic(afterPath, after);
    await writeJsonAtomic(comparisonPath, comparison);
    const audit = createMadSksAuditLedger({
        authorizationManifestPath: context.authorization_manifest_path || null,
        targetRoot: context.target_root,
        actions: auditActions,
        blockedActions
    });
    const rollback = createMadSksRollbackPlan({
        targetRoot: context.target_root,
        authorizationManifestPath: context.authorization_manifest_path || null,
        fileRollbacks,
        packageRollbacks,
        serviceRollbacks,
        dbRollbacks,
        unavailable: rollbackUnavailable
    });
    await writeMadSksAuditLedger(auditPath, audit);
    await writeMadSksRollbackPlan(rollbackPath, rollback);
    const proof = createMadSksProofEvidence({
        authorizationManifestPath: context.authorization_manifest_path || null,
        auditLedgerPath: auditPath,
        rollbackPlanPath: rollbackPath,
        protectedCoreBefore: beforePath,
        protectedCoreAfter: afterPath,
        protectedCoreComparison: comparison,
        changedTargetFiles: changedFiles,
        blockedActions,
        verification
    });
    await writeMadSksProofEvidence(proofPath, proof);
    return { auditPath, rollbackPath, proofPath, beforePath, afterPath, comparisonPath, audit, rollback, proof, comparison };
}
export async function fileContentSnapshot(file) {
    const exists = await pathExists(file);
    const content = exists ? await readText(file, '') : null;
    return {
        path: file,
        existed_before: exists,
        content,
        content_hash: content === null ? null : sha256(content)
    };
}
export async function writeRollbackSnapshot(context, snapshot) {
    const snapshotHash = sha256(`${snapshot.path}:${snapshot.content_hash || 'missing'}:${nowIso()}`);
    const snapshotPath = path.join(context.artifact_dir, 'rollback-snapshots', `${snapshotHash}.txt`);
    await ensureDir(path.dirname(snapshotPath));
    if (snapshot.content !== null)
        await writeTextAtomic(snapshotPath, snapshot.content);
    return snapshotPath;
}
export async function hashFileIfExists(file) {
    if (!(await pathExists(file)))
        return null;
    return sha256(await fsp.readFile(file));
}
export async function pathExists(file) {
    try {
        await fsp.access(file);
        return true;
    }
    catch {
        return false;
    }
}
export function resolveTargetPath(context, candidate) {
    const raw = String(candidate || '');
    if (!raw)
        return path.join(context.target_root, '.sneakoscope', 'mad-sks-target-file.txt');
    return path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(context.target_root, raw);
}
export function resultFromEvidence({ executor, actionType, context, status, changedFiles = [], evidence, verification = [], blockedActions = [], blockers = [], writesPerformed = false, extra = {} }) {
    return {
        schema: MAD_SKS_EXECUTOR_RESULT_SCHEMA,
        ok: blockers.length === 0 && evidence?.proof?.ok !== false,
        status,
        executor,
        action_type: actionType,
        target_root: context.target_root,
        changed_files: changedFiles,
        audit_ledger_path: evidence?.auditPath || null,
        rollback_plan_path: evidence?.rollbackPath || null,
        proof_evidence_path: evidence?.proofPath || null,
        verification,
        blocked_actions: blockedActions,
        blockers,
        writes_performed: writesPerformed,
        local_only_artifact_policy: true,
        generated_at: nowIso(),
        ...extra
    };
}
export function redactedCommand(command) {
    if (Array.isArray(command))
        return command.map((part) => redactMadSksSecrets(part)).join(' ');
    return redactMadSksSecrets(command || '');
}
//# sourceMappingURL=executor-base.js.map