import { buildProjectIndex } from "../project-index/index.js";
import { analyzeServiceDependencies, } from "../diagnostics/service-deps.js";
import { generateServicesDts } from "./generate-services-dts.js";
import { generateAppExtensionsDts, } from "./generate-app-extensions-dts.js";
import { writeServiceManifestFile } from "./write-service-manifest.js";
export async function runTypegen(options) {
    const { rootDir, generateServices, generateAppExtensions, checkOnly = false, writeManifest = false, } = options;
    const index = await buildProjectIndex(rootDir);
    const files = [];
    const warnings = [];
    if (generateServices) {
        files.push(await generateServicesDts(rootDir, index.serviceEntries, { checkOnly }));
    }
    if (generateAppExtensions) {
        const appExtensionsResult = await generateAppExtensionsDts(rootDir, index.appExtensions, { checkOnly });
        files.push(appExtensionsResult.file);
        warnings.push(...appExtensionsResult.warnings);
    }
    const serviceDeps = await analyzeServiceDependencies(rootDir);
    const manifest = writeManifest
        ? await writeServiceManifestFile(rootDir, index.serviceEntries, index.appExtensions, serviceDeps, { checkOnly })
        : undefined;
    const staleFiles = files.filter((file) => file.status === "stale");
    const staleManifest = manifest?.status === "stale";
    const hasErrors = staleFiles.length > 0 ||
        staleManifest ||
        serviceDeps.diagnostics.some((diagnostic) => diagnostic.level === "error");
    for (const staleFile of staleFiles) {
        warnings.push(`Generated file is stale: ${staleFile.filePath}`);
    }
    if (staleManifest && manifest) {
        warnings.push(`Generated file is stale: ${manifest.filePath}`);
    }
    return {
        ok: !hasErrors,
        files,
        diagnostics: serviceDeps.diagnostics,
        warnings,
        manifest,
    };
}
