import fs from 'node:fs/promises';
import path from 'node:path';
import { FragmentNotFoundError, PageNotFoundError } from '../content/provider.js';
import { normalizeRoute } from '../content/routes.js';
export class FileContentProvider {
    root;
    #manifest;
    constructor(root) {
        const resolved = root
            || process.env.ACI_CONTENT_ROOT
            || '.aci/compiled';
        this.root = path.resolve(process.cwd(), resolved);
    }
    async listRoutes() {
        const manifest = await this.manifest();
        return Object.values(manifest.routes).sort((a, b) => a.path.localeCompare(b.path));
    }
    async getSiteConfig() {
        const manifest = await this.manifest();
        return await this.readJSON(manifest.siteConfigRef);
    }
    async getPage(route) {
        const manifest = await this.manifest();
        const normalized = normalizeRoute(route);
        const entry = Object.values(manifest.routes).find((candidate) => normalizeRoute(candidate.path) === normalized);
        if (!entry) {
            throw new PageNotFoundError(route);
        }
        try {
            return await this.readJSON(entry.payloadRef);
        }
        catch (error) {
            throw new PageNotFoundError(route, error);
        }
    }
    async getFragment(id) {
        const manifest = await this.manifest();
        const entry = manifest.fragments[id];
        if (!entry) {
            throw new FragmentNotFoundError(id);
        }
        try {
            return await this.readJSON(entry.payloadRef);
        }
        catch (error) {
            throw new FragmentNotFoundError(id, error);
        }
    }
    async manifest() {
        this.#manifest ??= this.readJSON('manifest.json');
        return await this.#manifest;
    }
    async readJSON(key) {
        const raw = await fs.readFile(path.join(this.root, key), 'utf8');
        return JSON.parse(raw);
    }
}
