import { readJsonFile, writeJsonFile } from '../lib/json.js';
import { getStatePath } from '../lib/paths.js';
const REVIEW_STATE_PATH = getStatePath('data/system/review-state.json');
const REVIEW_TTL_MS = 24 * 60 * 60 * 1000;
export async function recordItemReview(id, via) {
    const state = await loadReviewState();
    state.reviews[id] = {
        reviewedAt: new Date().toISOString(),
        via
    };
    await writeJsonFile(REVIEW_STATE_PATH, state);
}
export async function hasRecentReview(id, now = Date.now()) {
    const receipt = await getReviewReceipt(id);
    if (!receipt) {
        return false;
    }
    const reviewedAtMs = Date.parse(receipt.reviewedAt);
    if (Number.isNaN(reviewedAtMs)) {
        return false;
    }
    return now - reviewedAtMs <= REVIEW_TTL_MS;
}
export async function assertRecentReview(id) {
    if (await hasRecentReview(id)) {
        return;
    }
    throw new Error(`Review required before install for ${id}. Run \`plugscout show --id ${id}\` or \`plugscout assess --id ${id}\`, then retry. Use --override-review only if you intentionally want to bypass this safeguard.`);
}
export function getReviewStatePath() {
    return REVIEW_STATE_PATH;
}
async function getReviewReceipt(id) {
    const state = await loadReviewState();
    return state.reviews[id] ?? null;
}
async function loadReviewState() {
    try {
        const raw = await readJsonFile(REVIEW_STATE_PATH);
        if (!raw || typeof raw !== 'object') {
            return { reviews: {} };
        }
        const reviews = raw.reviews;
        if (!reviews || typeof reviews !== 'object') {
            return { reviews: {} };
        }
        const normalized = {};
        Object.entries(reviews).forEach(([id, value]) => {
            if (!value || typeof value !== 'object') {
                return;
            }
            const reviewedAt = typeof value.reviewedAt === 'string'
                ? value.reviewedAt
                : null;
            const via = value.via;
            if (!reviewedAt || (via !== 'show' && via !== 'assess')) {
                return;
            }
            normalized[id] = { reviewedAt, via };
        });
        return { reviews: normalized };
    }
    catch (error) {
        const maybeFsError = error;
        if (maybeFsError.code === 'ENOENT') {
            return { reviews: {} };
        }
        throw error;
    }
}
