import { Dt as theme, _ as defaultRuntime } from "./entry.js";
import { r as getToolPrivacyDeclaration, t as AuditStore } from "./audit-store-NOnPaYIH.js";
import { t as formatHelpExamples } from "./help-format-CSTLKmFP.js";
import os from "node:os";
import path from "node:path";
import fs from "node:fs";
import crypto from "node:crypto";

//#region src/audit/audit-report.ts
/**
* AudAgent C: Compliance report generator for EU AI Act Article 50.
*
* Reads JSONL audit logs produced by AuditStore (Phase B) and generates
* a structured transparency report satisfying Article 50 requirements.
*
* Reference: arXiv:2511.07441 — AudAgent compliance report format
*/
/**
* Generate a compliance report from audit log entries in the given window.
*
* Aggregate per-tool data flows, collect all violations, and compute a
* tamper-evident hash over the raw JSONL content for the report period.
*/
async function generateComplianceReport(opts = {}) {
	const end = opts.end ?? /* @__PURE__ */ new Date();
	const start = opts.start ?? /* @__PURE__ */ new Date(end.getTime() - 720 * 60 * 60 * 1e3);
	const auditDir = opts.auditDir ?? path.join(os.homedir(), ".minion", "audit");
	const policyVersion = opts.policyVersion ?? "1.0.0";
	const entries = await new AuditStore({
		dir: auditDir,
		enabled: true
	}).readRange(start, end);
	const auditLogHash = await computeAuditLogHash(auditDir, start, end);
	const flowMap = /* @__PURE__ */ new Map();
	const allViolations = [];
	for (const entry of entries) {
		allViolations.push(...entry.violations);
		const existing = flowMap.get(entry.toolName);
		if (existing) {
			mergeDataCategories(existing.dataCategories, entry.paramCategories);
			if (entry.resultCategories) mergeDataCategories(existing.dataCategories, entry.resultCategories);
			existing.invocationCount++;
			existing.violationCount += entry.violations.length;
		} else {
			const decl = lookupToolDeclaration(entry);
			const categories = [...entry.paramCategories];
			if (entry.resultCategories) mergeDataCategories(categories, entry.resultCategories);
			flowMap.set(entry.toolName, {
				tool: entry.toolName,
				vendor: decl.vendor,
				dataCategories: categories,
				consentScope: entry.consentScope,
				invocationCount: 1,
				thirdParty: decl.externalTransfer,
				violationCount: entry.violations.length
			});
		}
	}
	return {
		reportDate: (/* @__PURE__ */ new Date()).toISOString(),
		period: {
			start: start.toISOString(),
			end: end.toISOString()
		},
		totalToolInvocations: entries.length,
		totalViolations: allViolations.length,
		dataFlows: Array.from(flowMap.values()).toSorted((a, b) => b.invocationCount - a.invocationCount),
		violations: allViolations,
		auditLogHash,
		policyVersion
	};
}
function mergeDataCategories(target, incoming) {
	for (const cat of incoming) if (!target.includes(cat)) target.push(cat);
}
function lookupToolDeclaration(entry) {
	const decl = getToolPrivacyDeclaration(entry.toolName);
	return {
		vendor: decl.vendor,
		externalTransfer: decl.externalTransfer
	};
}
/**
* Compute a SHA-256 hash over all raw JSONL content for audit files covering
* the [from, to] date range. Files that do not exist are skipped.
*
* The hash provides a tamper-evident fingerprint for the report period.
*/
async function computeAuditLogHash(dir, from, to) {
	const hash = crypto.createHash("sha256");
	const cursor = new Date(from);
	cursor.setHours(0, 0, 0, 0);
	const endDay = new Date(to);
	endDay.setHours(23, 59, 59, 999);
	while (cursor <= endDay) {
		const dateStr = cursor.toISOString().slice(0, 10);
		const filePath = path.join(dir, `audit-${dateStr}.jsonl`);
		try {
			const content = await fs.promises.readFile(filePath);
			hash.update(content);
		} catch (err) {
			if (err.code !== "ENOENT") throw err;
		}
		cursor.setDate(cursor.getDate() + 1);
	}
	return `sha256:${hash.digest("hex")}`;
}
function formatReportAsMarkdown(report) {
	const lines = [];
	lines.push("# EU AI Act Article 50 — Transparency Report");
	lines.push("");
	lines.push(`**Generated:** ${report.reportDate}`);
	lines.push(`**Period:** ${report.period.start} → ${report.period.end}`);
	lines.push(`**Policy version:** ${report.policyVersion}`);
	lines.push(`**Audit log hash:** \`${report.auditLogHash}\``);
	lines.push("");
	lines.push("## Summary");
	lines.push("");
	lines.push(`| Metric | Value |`);
	lines.push(`|--------|-------|`);
	lines.push(`| Total tool invocations | ${report.totalToolInvocations} |`);
	lines.push(`| Total violations | ${report.totalViolations} |`);
	lines.push(`| Distinct tools | ${report.dataFlows.length} |`);
	lines.push("");
	lines.push("## Data Flows");
	lines.push("");
	lines.push("| Tool | Vendor | Data Categories | Consent Scope | Invocations | Third-Party | Violations |");
	lines.push("|------|--------|----------------|---------------|------------|-------------|-----------|");
	for (const flow of report.dataFlows) {
		const cats = flow.dataCategories.join(", ") || "none";
		lines.push(`| ${flow.tool} | ${flow.vendor} | ${cats} | ${flow.consentScope} | ${flow.invocationCount} | ${flow.thirdParty ? "yes" : "no"} | ${flow.violationCount} |`);
	}
	lines.push("");
	if (report.violations.length > 0) {
		lines.push("## Violations");
		lines.push("");
		for (const v of report.violations) lines.push(`- **${v.type}**: ${v.detail}`);
		lines.push("");
	}
	return lines.join("\n");
}
function formatReportAsHtml(report) {
	return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>EU AI Act Article 50 — Transparency Report</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 900px; margin: 2rem auto; padding: 0 1rem; }
    table { border-collapse: collapse; width: 100%; }
    th, td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
    th { background: #f5f5f5; }
    code { background: #f0f0f0; padding: 2px 4px; border-radius: 3px; font-size: 0.9em; }
    h1, h2 { border-bottom: 1px solid #eee; padding-bottom: 0.3em; }
  </style>
</head>
<body>
<pre style="white-space:pre-wrap">${escapeHtml(formatReportAsMarkdown(report))}</pre>
</body>
</html>`;
}
function escapeHtml(s) {
	return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
function formatReport(report, format) {
	switch (format) {
		case "json": return JSON.stringify(report, null, 2);
		case "markdown": return formatReportAsMarkdown(report);
		case "html": return formatReportAsHtml(report);
	}
}

//#endregion
//#region src/cli/audit-cli.ts
function parseDate(raw, fallback) {
	if (!raw) return fallback;
	const d = new Date(raw);
	if (isNaN(d.getTime())) throw new Error(`Invalid date: ${raw}`);
	return d;
}
function registerAuditCli(program) {
	program.command("audit").description("EU AI Act Article 50 compliance tools").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
		["minion audit report", "Generate a compliance report for the last 30 days (JSON)."],
		["minion audit report --format markdown", "Output as Markdown."],
		["minion audit report --format html --start 2026-01-01", "HTML report from Jan 1."],
		["minion audit report --start 2026-03-01 --end 2026-03-31", "March 2026 window."]
	])}\n`).command("report").description("Generate a compliance transparency report (EU AI Act Article 50)").option("--start <date>", "Start of audit window (ISO8601 date or datetime)").option("--end <date>", "End of audit window (ISO8601 date or datetime, default: now)").option("--format <format>", "Output format: json | markdown | html (default: json)", "json").option("--dir <path>", "Audit log directory (default: ~/.minion/audit)").option("--policy-version <version>", "Privacy policy version string (default: 1.0.0)").action(async (opts) => {
		const now = /* @__PURE__ */ new Date();
		const end = parseDate(opts.end, now);
		const start = parseDate(opts.start, /* @__PURE__ */ new Date(end.getTime() - 720 * 60 * 60 * 1e3));
		const format = opts.format ?? "json";
		if (![
			"json",
			"markdown",
			"html"
		].includes(format)) {
			defaultRuntime.log(`Error: --format must be one of: json, markdown, html`);
			process.exitCode = 1;
			return;
		}
		const report = await generateComplianceReport({
			start,
			end,
			format,
			auditDir: opts.dir,
			policyVersion: opts.policyVersion
		});
		defaultRuntime.log(formatReport(report, format));
	});
}

//#endregion
export { registerAuditCli };