import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import { getModel, type Api, type Model } from "@earendil-works/pi-ai";
import { configFromEnv, runObserver } from "../src/observer.ts";
import { replay } from "../src/state.ts";

const key = JSON.parse(readFileSync(join(homedir(), ".prime/agent/auth.json"), "utf8")).google.key as string;
const cfg = configFromEnv(process.env);
const lookup = getModel as unknown as (provider: string, modelId: string) => Model<Api> | undefined;
const model = lookup(cfg.provider, cfg.modelId);
const modelRegistry = {
	find: () => model,
	getApiKeyAndHeaders: async () => ({ ok: true, apiKey: key, headers: {} }),
};
const registry = replay([
	{ kind: "user_message", messageId: "m1", text: "add retry logic and update the docs", at: 1 },
]);
const messages = [
	{
		role: "assistant",
		content: [{ type: "text", text: "The retry logic is complete. The docs still need work." }],
		stopReason: "stop",
		timestamp: Date.now(),
	},
] as unknown as AgentMessage[];

const result = await runObserver(registry, messages, new Set(["m1"]), modelRegistry as never, {
	...cfg,
	apiKey: key,
});
console.log(JSON.stringify(result, null, 2));
