import { ConfigSchema, init_schema } from "../../../../config/schema.js";
import { init_loader, loadConfig, saveConfig } from "../../../../config/loader.js";
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname } from "node:path";
//#region src/cli/commands/doctor/checks/config-health.ts
init_loader();
init_schema();
async function checkConfigHealth(ctx) {
	const path = ctx.configPath;
	if (!existsSync(path)) {
		if (ctx.options.fix) try {
			mkdirSync(dirname(path), { recursive: true });
			await saveConfig(loadConfig(path), path);
			return {
				id: "config-health",
				label: "Config",
				status: "pass",
				message: "Created default config file.",
				hints: [path],
				fixed: true
			};
		} catch (e) {
			return {
				id: "config-health",
				label: "Config",
				status: "fail",
				message: `Config file missing and could not create default: ${e instanceof Error ? e.message : String(e)}`,
				hints: [path]
			};
		}
		return {
			id: "config-health",
			label: "Config",
			status: "fail",
			message: "Config file not found.",
			hints: [`Run: xopc init (or xopc setup)`, `Or: xopc doctor --fix`]
		};
	}
	let raw;
	try {
		raw = readFileSync(path, "utf-8");
	} catch (e) {
		return {
			id: "config-health",
			label: "Config",
			status: "fail",
			message: `Cannot read config file: ${e instanceof Error ? e.message : String(e)}`,
			hints: [path]
		};
	}
	let json;
	try {
		json = JSON.parse(raw);
	} catch {
		return {
			id: "config-health",
			label: "Config",
			status: "fail",
			message: "Config file is not valid JSON.",
			hints: ["Fix syntax or restore from backup (.bak).", path]
		};
	}
	const parsed = ConfigSchema.safeParse(json);
	if (!parsed.success) return {
		id: "config-health",
		label: "Config",
		status: "fail",
		message: "Config does not match the expected schema.",
		hints: parsed.error.issues.slice(0, 5).map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`)
	};
	return {
		id: "config-health",
		label: "Config",
		status: "pass",
		message: "Config file exists and validates.",
		hints: [path]
	};
}
//#endregion
export { checkConfigHealth };

//# sourceMappingURL=config-health.js.map