import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";

const MOBILE = {serverPort: Number(process.env.PROOF_SERVER_PORT)};
const MOBILE_T3_HOME = process.env.PROOF_HOME!;
import { rpcClient, runPromise, makeState } from "./t3.ts";


const t3 = makeState(MOBILE_T3_HOME, {T3CODE_PORT: String(MOBILE.serverPort)}).state;
const project = await t3.project("usage-demo");
    const seed = async (boundary = false) => { await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        const path = yield* Path.Path;
        const timestamp = DateTime.formatIso(yield* DateTime.now);
        const piSessions = path.join(MOBILE_T3_HOME, "pi-history");
        const codexHome = path.join(MOBILE_T3_HOME, "usage-codex");
        const codexSessions = path.join(codexHome, "sessions");
        const jsonLines = (entries: readonly unknown[]) =>
          entries.map((entry) => JSON.stringify(entry)).join("\n") + "\n";
        yield* fs.makeDirectory(piSessions, { recursive: true });
        yield* fs.makeDirectory(codexSessions, { recursive: true });
        yield* fs.writeFileString(
          path.join(piSessions, "session.jsonl"),
          jsonLines([
            { type: "session", version: 3, id: "demo", timestamp, cwd: project },
            {
              type: "message",
              id: "reply",
              parentId: null,
              timestamp,
              message: {
                role: "assistant",
                provider: "anthropic",
                model: "fixture-model",
                usage: { input: 100, cost: { total: 0.02 } },
              },
            },
          ]),
        );
        yield* fs.writeFileString(
          path.join(codexSessions, "rollout.jsonl"),
          jsonLines([
            { type: "session_meta", timestamp, payload: { id: "demo" } },
            { type: "turn_context", timestamp, payload: { model: "gpt-6.2-sol" } },
            {
              type: "event_msg",
              timestamp,
              payload: {
                type: "token_count",
                info: { last_token_usage: { input_tokens: boundary ? 199999 : 700, output_tokens: 0 } },
              },
            },
          ]),
        );
        if (boundary) yield* fs.writeFileString(
          path.join(codexSessions, "unpriced.jsonl"),
          jsonLines([
            { type: "session_meta", timestamp, payload: { id: "unpriced" } },
            { type: "turn_context", timestamp, payload: { model: "unknown-usage-model" } },
            { type: "event_msg", timestamp, payload: { type: "token_count", info: { last_token_usage: { input_tokens: 1, output_tokens: 0 } } } },
          ]),
        );
        const client = yield* rpcClient(MOBILE_T3_HOME, `http://127.0.0.1:${MOBILE.serverPort}`);
        const binaryPath = path.join(MOBILE_T3_HOME, "bin", "no-model");
        yield* client["server.updateSettings"]({
          patch: {},
          providerInstanceMutation: {
            operation: "upsert",
            instanceId: ProviderInstanceId.make("pi"),
            instance: {
              driver: ProviderDriverKind.make("pi"),
              enabled: true,
              usageAccess: "allowed",
              config: { binaryPath },
              environment: [
                { name: "PI_CODING_AGENT_SESSION_DIR", value: piSessions, sensitive: false },
              ],
            },
          },
        });
        yield* client["server.updateSettings"]({
          patch: {},
          providerInstanceMutation: {
            operation: "upsert",
            instanceId: ProviderInstanceId.make("usage-codex"),
            instance: {
              driver: ProviderDriverKind.make("codex"),
              enabled: true,
              usageAccess: "allowed",
              config: { setupMode: "existing", binaryPath, homePath: codexHome },
            },
          },
        });
      }).pipe(Effect.scoped),
    );
    };
    await seed(process.argv.includes("--boundary"));

