import fs from "node:fs";
import os from "node:os";
import path from "node:path";

//#region src/audit/tool-privacy-policy.ts
const KNOWN_TOOLS = {
	web_search: {
		toolName: "web_search",
		vendor: "third-party",
		dataCategories: ["user_content", "message_history"],
		externalTransfer: true,
		retentionPolicy: "unknown",
		gdprLegalBasis: "Art.6(1)(b) - contract performance"
	},
	web_fetch: {
		toolName: "web_fetch",
		vendor: "third-party",
		dataCategories: ["user_content"],
		externalTransfer: true,
		retentionPolicy: "unknown"
	},
	browse_web: {
		toolName: "browse_web",
		vendor: "third-party",
		dataCategories: ["user_content", "message_history"],
		externalTransfer: true,
		retentionPolicy: "unknown"
	},
	bash: {
		toolName: "bash",
		vendor: "local",
		dataCategories: ["file_content", "credentials"],
		externalTransfer: false,
		retentionPolicy: "session-only"
	},
	computer: {
		toolName: "computer",
		vendor: "local",
		dataCategories: [
			"file_content",
			"credentials",
			"user_content"
		],
		externalTransfer: false,
		retentionPolicy: "session-only"
	},
	execute_command: {
		toolName: "execute_command",
		vendor: "local",
		dataCategories: ["file_content", "credentials"],
		externalTransfer: false,
		retentionPolicy: "session-only"
	},
	read_file: {
		toolName: "read_file",
		vendor: "local",
		dataCategories: ["file_content"],
		externalTransfer: false,
		retentionPolicy: "session-only"
	},
	write_file: {
		toolName: "write_file",
		vendor: "local",
		dataCategories: ["file_content", "user_content"],
		externalTransfer: false,
		retentionPolicy: "indefinite"
	},
	list_files: {
		toolName: "list_files",
		vendor: "local",
		dataCategories: ["metadata"],
		externalTransfer: false,
		retentionPolicy: "session-only"
	},
	memory_search: {
		toolName: "memory_search",
		vendor: "local",
		dataCategories: ["user_content", "message_history"],
		externalTransfer: false,
		retentionPolicy: "indefinite"
	},
	memory_store: {
		toolName: "memory_store",
		vendor: "local",
		dataCategories: [
			"user_content",
			"message_history",
			"user_identity"
		],
		externalTransfer: false,
		retentionPolicy: "indefinite"
	},
	llm_call: {
		toolName: "llm_call",
		vendor: "third-party",
		dataCategories: ["user_content", "message_history"],
		externalTransfer: true,
		retentionPolicy: "unknown",
		gdprLegalBasis: "Art.6(1)(b) - contract performance"
	},
	anthropic_messages: {
		toolName: "anthropic_messages",
		vendor: "anthropic",
		dataCategories: ["user_content", "message_history"],
		externalTransfer: true,
		retentionPolicy: "30-days",
		gdprLegalBasis: "Art.6(1)(b) - contract performance"
	},
	openai_chat: {
		toolName: "openai_chat",
		vendor: "openai",
		dataCategories: ["user_content", "message_history"],
		externalTransfer: true,
		retentionPolicy: "30-days",
		gdprLegalBasis: "Art.6(1)(b) - contract performance"
	},
	send_email: {
		toolName: "send_email",
		vendor: "third-party",
		dataCategories: ["user_content", "user_identity"],
		externalTransfer: true,
		retentionPolicy: "unknown",
		gdprLegalBasis: "Art.6(1)(b) - contract performance"
	},
	send_message: {
		toolName: "send_message",
		vendor: "local",
		dataCategories: ["user_content", "user_identity"],
		externalTransfer: false,
		retentionPolicy: "session-only"
	},
	code_interpreter: {
		toolName: "code_interpreter",
		vendor: "local",
		dataCategories: ["file_content", "user_content"],
		externalTransfer: false,
		retentionPolicy: "session-only"
	}
};
const UNKNOWN_TOOL_CATEGORIES = ["user_content", "metadata"];
/**
* Return the privacy declaration for a named tool.
*
* Falls back to a conservative unknown-tool declaration when the tool
* is not in the built-in registry.
*/
function getToolPrivacyDeclaration(toolName) {
	const known = KNOWN_TOOLS[toolName.trim().toLowerCase()];
	if (known !== void 0) return known;
	return {
		toolName,
		vendor: "unknown",
		dataCategories: UNKNOWN_TOOL_CATEGORIES,
		externalTransfer: true,
		retentionPolicy: "unknown"
	};
}

//#endregion
//#region src/audit/audit-store.ts
/**
* AuditStore — append-only JSONL audit log writer.
*
* Compliance requirements:
* - One record per line (JSONL / newline-delimited JSON)
* - Files rotate daily: audit-YYYY-MM-DD.jsonl
* - Entries are flushed to disk immediately after each write (no buffering)
* - Files are never deleted or truncated, only appended
*/
var AuditStore = class {
	constructor(opts) {
		this.writeChain = Promise.resolve();
		this.dir = opts.dir;
		this.enabled = opts.enabled;
	}
	getFilePath(date) {
		const dateStr = date.toISOString().slice(0, 10);
		return path.join(this.dir, `audit-${dateStr}.jsonl`);
	}
	/**
	* Append one AuditEntry to today's log file.
	*
	* Writes are serialized through an internal queue so that concurrent
	* fire-and-forget calls (e.g. from the audit plugin's after_tool_call
	* hook) are written in enqueue order, not in I/O-settlement order.
	*
	* Each write is flushed to disk immediately (compliance: no buffering).
	* Creates the log directory if it does not exist.
	*/
	append(entry) {
		if (!this.enabled) return Promise.resolve();
		this.writeChain = this.writeChain.then(() => this.writeEntry(entry));
		return this.writeChain;
	}
	async writeEntry(entry) {
		await fs.promises.mkdir(this.dir, { recursive: true });
		const filePath = this.getFilePath(/* @__PURE__ */ new Date());
		const line = `${JSON.stringify(entry)}\n`;
		const fd = await fs.promises.open(filePath, "a");
		try {
			await fd.write(line);
			await fd.datasync();
		} finally {
			await fd.close();
		}
	}
	/**
	* Read all AuditEntries with timestamps in [from, to].
	*
	* Iterates daily log files covering the range. Skips missing files
	* (days with no audit activity). Skips malformed lines silently.
	*/
	async readRange(from, to) {
		const entries = [];
		if (!this.enabled) return entries;
		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 filePath = this.getFilePath(cursor);
			try {
				const content = await fs.promises.readFile(filePath, "utf-8");
				for (const raw of content.split("\n")) {
					const line = raw.trim();
					if (!line) continue;
					try {
						const entry = JSON.parse(line);
						const ts = new Date(entry.timestamp);
						if (ts >= from && ts <= to) entries.push(entry);
					} catch {}
				}
			} catch (err) {
				if (err.code !== "ENOENT") throw err;
			}
			cursor.setDate(cursor.getDate() + 1);
		}
		return entries;
	}
};
/** Create an AuditStore with defaults suitable for production use. */
function createAuditStore(opts = {}) {
	return new AuditStore({
		dir: opts.dir ?? path.join(os.homedir(), ".minion", "audit"),
		enabled: opts.enabled ?? true
	});
}

//#endregion
export { createAuditStore as n, getToolPrivacyDeclaration as r, AuditStore as t };