import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { execSync } from "node:child_process";
//#region extensions/crypto/src/services/issue-reporter.ts
/**
* Issue Reporter Service — file GitHub issues from chat.
*
* Persistent opt-in per user. When enabled, the agent can proactively
* suggest filing issues when it detects bugs, errors, or UX problems.
*
* Issues are filed via `gh issue create` against the openclawnch repo.
* Requires `gh` CLI installed and authenticated.
*/
const REPO = "clawnchdev/openclawnch";
const MAX_BODY_CHARS = 4e3;
const DEFAULT_CONFIG = {
	enabled: false,
	issueCount: 0
};
const configCache = /* @__PURE__ */ new Map();
function getStateDir() {
	return process.env.OPENCLAWNCH_STATE_DIR ? join(process.env.OPENCLAWNCH_STATE_DIR, "issue-reporter") : join(process.env.HOME ?? "/tmp", ".openclawnch", "issue-reporter");
}
function ensureDir() {
	const dir = getStateDir();
	if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
}
function sanitizeUserId(userId) {
	return userId.replace(/[^a-zA-Z0-9_\-. ]/g, "_").slice(0, 64);
}
function configPath(userId) {
	return join(getStateDir(), `${sanitizeUserId(userId)}.json`);
}
function getReporterConfig(userId) {
	const cached = configCache.get(userId);
	if (cached) return cached;
	const path = configPath(userId);
	if (existsSync(path)) try {
		const raw = JSON.parse(readFileSync(path, "utf8"));
		configCache.set(userId, raw);
		return raw;
	} catch {}
	return { ...DEFAULT_CONFIG };
}
function isReportingEnabled(userId) {
	return getReporterConfig(userId).enabled;
}
function enableReporting(userId) {
	ensureDir();
	const config = {
		...getReporterConfig(userId),
		enabled: true,
		optedInAt: (/* @__PURE__ */ new Date()).toISOString()
	};
	writeFileSync(configPath(userId), JSON.stringify(config, null, 2));
	configCache.set(userId, config);
}
function disableReporting(userId) {
	ensureDir();
	const config = {
		...getReporterConfig(userId),
		enabled: false
	};
	writeFileSync(configPath(userId), JSON.stringify(config, null, 2));
	configCache.set(userId, config);
}
/**
* File a GitHub issue. Returns the issue URL on success.
*
* Labels are auto-applied:
*   - `from-agent` on every issue
*   - `bug` / `enhancement` / `question` based on the category param
*/
function fileIssue(opts) {
	const config = getReporterConfig(opts.userId);
	if (!config.enabled) return { error: "Issue reporting is not enabled. Use /report_opt_in to enable." };
	try {
		execSync("gh auth status", {
			stdio: "pipe",
			timeout: 5e3
		});
	} catch {
		return { error: "GitHub CLI (gh) is not authenticated. Run `gh auth login` first." };
	}
	const label = {
		bug: "bug",
		feature: "enhancement",
		ux: "ux",
		question: "question"
	}[opts.category] ?? "bug";
	const fullBody = [
		opts.body.length > MAX_BODY_CHARS ? opts.body.slice(0, MAX_BODY_CHARS) + "\n\n---\n*[Truncated — full context exceeded limit]*" : opts.body,
		"",
		"---",
		`*Filed by OpenClawnch agent on behalf of user. Category: ${opts.category}.*`
	].join("\n");
	try {
		const result = execSync(`gh issue create --repo ${REPO} --title ${shellEscape(opts.title)} --body ${shellEscape(fullBody)} --label from-agent --label ${shellEscape(label)}`, {
			encoding: "utf8",
			timeout: 15e3,
			stdio: "pipe"
		}).trim();
		const url = result.split("\n").pop() ?? result;
		ensureDir();
		const updated = {
			...config,
			issueCount: config.issueCount + 1
		};
		writeFileSync(configPath(opts.userId), JSON.stringify(updated, null, 2));
		configCache.set(opts.userId, updated);
		return { url };
	} catch (err) {
		const msg = err instanceof Error ? err.message : String(err);
		if (msg.includes("label")) try {
			const result = execSync(`gh issue create --repo ${REPO} --title ${shellEscape(opts.title)} --body ${shellEscape(fullBody)}`, {
				encoding: "utf8",
				timeout: 15e3,
				stdio: "pipe"
			}).trim();
			return { url: result.split("\n").pop() ?? result };
		} catch (retryErr) {
			return { error: `Failed to create issue: ${retryErr instanceof Error ? retryErr.message : String(retryErr)}` };
		}
		return { error: `Failed to create issue: ${msg}` };
	}
}
/** Reset for testing. */
function resetReporter() {
	configCache.clear();
}
function shellEscape(s) {
	return "$'" + s.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n") + "'";
}
//#endregion
export { disableReporting, enableReporting, fileIssue, getReporterConfig, isReportingEnabled, resetReporter };

//# sourceMappingURL=issue-reporter.mjs.map