import { handleSkillInstall } from '../skill-registry/index.js';
import { autoInstallRecommendedSkills } from './skill-auto-installer.js';
import { checkProjectHealth, } from '../../engine/project-health-checker.js';
import { saveBaseline } from '../../storage/convention-baseline.js';
import { scanProject } from '../../engine/project-scanner/index.js';
import { isTelemetryEnabled, hasNeverBeenPrompted, markAsPrompted, getOrCreateInstallationId, sendTelemetryEvent, } from '../../engine/telemetry/index.js';
import { generateProjectRules, writeRules } from '../../engine/rules-generator/index.js';
import { getWhatsNew } from '../../engine/whats-new.js';
import { PLANU_VERSION } from '../../config/version.js';
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
/** SPEC-192: Run health check and store convention baseline (best-effort). */
export async function runHealthCheckWithBaseline(projectPath, projectId, knowledge, specSummaries) {
    try {
        const report = await checkProjectHealth(projectPath, knowledge, specSummaries);
        if (report.conventionScan) {
            await saveBaseline(projectId, {
                projectId,
                snapshot: report.conventionScan,
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString(),
            }).catch((err) => {
                console.warn('[Planu] Failed to save convention baseline:', err instanceof Error ? err.message : String(err));
            });
        }
        return report;
    }
    catch {
        return null;
    }
}
/**
 * Read autoInstallSkills flag from planu.json (best-effort).
 * Default is true (opt-out): returns false only when explicitly set to false.
 */
export async function readAutoInstallFlag(configPath) {
    try {
        const raw = JSON.parse(await readFile(configPath, 'utf-8'));
        if (typeof raw === 'object' &&
            raw !== null &&
            'autoInstallSkills' in raw &&
            raw.autoInstallSkills === false) {
            return false;
        }
        return true;
    }
    catch {
        return true;
    }
}
/** Install recommended skills or queue them for manual install (best-effort). */
export async function resolveSkillInstalls(skills, projectPath, autoInstall) {
    const skillsAutoInstalled = [];
    const skillsPendingInstall = [];
    for (const skill of skills) {
        if (autoInstall) {
            try {
                const result = await handleSkillInstall({ name: skill.name, projectPath });
                if (!result.isError) {
                    skillsAutoInstalled.push(skill.name);
                }
                else {
                    skillsPendingInstall.push(skill.name);
                }
            }
            catch {
                skillsPendingInstall.push(skill.name);
            }
        }
        else {
            skillsPendingInstall.push(skill.name);
        }
    }
    return { skillsAutoInstalled, skillsPendingInstall };
}
/** Extract "What's New" highlights by comparing lastSeenVersion in planu.json (best-effort). */
export async function checkWhatsNew(configPath) {
    try {
        const raw = JSON.parse(await readFile(configPath, 'utf-8'));
        const lastSeen = typeof raw === 'object' && raw !== null && 'lastSeenVersion' in raw
            ? String(raw.lastSeenVersion)
            : '0.0.0';
        const result = getWhatsNew(lastSeen, PLANU_VERSION);
        // Update lastSeenVersion in config (fire-and-forget)
        if (result !== null || lastSeen !== PLANU_VERSION) {
            const updated = { ...raw, lastSeenVersion: PLANU_VERSION };
            await writeFile(configPath, JSON.stringify(updated, null, 2) + '\n', 'utf-8');
        }
        return result;
    }
    catch {
        return null;
    }
}
export function generateAndWriteRules(projectPath) {
    try {
        const aiRules = generateProjectRules(projectPath);
        return writeRules(aiRules);
    }
    catch {
        return { written: [], skipped: [] };
    }
}
export async function fireTelemetry(knowledge) {
    const [enabled, neverPrompted, installationId] = await Promise.all([
        isTelemetryEnabled().catch(() => false),
        hasNeverBeenPrompted().catch(() => false),
        getOrCreateInstallationId().catch(() => ''),
    ]);
    if (enabled && installationId) {
        sendTelemetryEvent({
            event: 'init_project',
            properties: {
                stack: knowledge.stack,
                language: knowledge.language,
                framework: knowledge.framework ?? null,
                platform: process.platform,
                nodeVersion: process.version,
                specCount: knowledge.specCount ?? 0,
            },
            installationId,
        });
    }
    if (neverPrompted) {
        void markAsPrompted().catch((_e) => undefined);
    }
    return neverPrompted;
}
/** SPEC-228: Run convention scan and write planu/conventions.json (best-effort). */
async function runConventionScan(projectPath) {
    const result = await scanProject(projectPath);
    const planuDir = join(projectPath, 'planu');
    await mkdir(planuDir, { recursive: true });
    await writeFile(join(planuDir, 'conventions.json'), JSON.stringify(result, null, 2) + '\n', 'utf-8');
}
export async function runConventionScanSafe(projectPath) {
    try {
        await runConventionScan(projectPath);
        return 'ok';
    }
    catch (err) {
        console.warn('[Planu] convention scan failed:', err instanceof Error ? err.message : String(err));
        return 'failed';
    }
}
/** Orchestrate skill discovery and installation with autoInstall logic. */
export async function orchestrateSkillInstalls(recommendedSkills, projectPath, autoInstallFromConfig) {
    const autoInstall = recommendedSkills.length > 0 && autoInstallFromConfig;
    if (autoInstall) {
        const installSummary = await autoInstallRecommendedSkills(projectPath, recommendedSkills);
        return {
            skillsAutoInstalled: installSummary.installed,
            skillsSkipped: installSummary.skipped,
            skillsPendingInstall: installSummary.failed.map((f) => f.name),
        };
    }
    const { skillsAutoInstalled, skillsPendingInstall } = await resolveSkillInstalls(recommendedSkills, projectPath, false);
    return { skillsAutoInstalled, skillsPendingInstall, skillsSkipped: [] };
}
//# sourceMappingURL=lifecycle-helpers.js.map