import { spawnSync } from "node:child_process";
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DEFAULT_BASE_URL } from "../client.js";
import { readConfig, writeConfig } from "./config.js";

/**
 * The anonymous free-tier signup flow. Freestyle serves a single-use
 * attestation binary; running it produces an opaque token that the server
 * validates and — if the device/project looks like a real developer/agent —
 * exchanges for a brand-new free-tier account and an API key. No Stack login is
 * involved; the account is claimable later (`freestyle claim`).
 */
export interface AnonymousAccount {
  apiKey: string;
  accountId: string;
  tier: string;
  allocationBand?: string;
  grantedCredits?: number;
  guidance?: string;
}

export interface CreateAnonymousOptions {
  /** Gateway base URL; defaults to FREESTYLE_PROXY or the public API. */
  baseUrl?: string;
  /** Optional one-line description of what you're building. */
  useCase?: string;
}

function resolveBaseUrl(options: CreateAnonymousOptions): string {
  return (options.baseUrl ?? process.env.FREESTYLE_PROXY ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
}

/** Create a fresh anonymous free-tier account and return its API key. */
export async function createAnonymousAccount(
  options: CreateAnonymousOptions = {},
): Promise<AnonymousAccount> {
  // The attestation binary is a Linux x86-64 executable. Agents and CI run
  // there; a laptop CLI on macOS/Windows can't produce a token, so point the
  // user at the ordinary login instead of failing obscurely.
  if (process.platform !== "linux" || process.arch !== "x64") {
    throw new Error(
      `Anonymous accounts are created by running a Linux x86-64 attestation binary, which ` +
        `this host (${process.platform}/${process.arch}) can't run. Use \`freestyle login\`, ` +
        `or set FREESTYLE_API_KEY.`,
    );
  }

  const baseUrl = resolveBaseUrl(options);
  const useCase = options.useCase ?? process.env.FREESTYLE_USE_CASE;

  // 1. Fetch the per-request attestation binary.
  const binaryResponse = await fetch(`${baseUrl}/v5/free-tier/binary`);
  if (!binaryResponse.ok) {
    throw new Error(
      `Could not fetch the signup binary (HTTP ${binaryResponse.status}). Anonymous signup may ` +
        `be unavailable on this deployment.`,
    );
  }
  const binary = Buffer.from(await binaryResponse.arrayBuffer());

  // 2. Run it to produce a token, in a throwaway dir.
  const dir = mkdtempSync(join(tmpdir(), "freestyle-fp-"));
  const binaryPath = join(dir, "freestyle-fp");
  let token: string;
  try {
    writeFileSync(binaryPath, binary);
    chmodSync(binaryPath, 0o755);
    const env = { ...process.env } as NodeJS.ProcessEnv;
    if (useCase) env.FREESTYLE_USE_CASE = useCase;
    const run = spawnSync(binaryPath, [], {
      env,
      encoding: "utf8",
      maxBuffer: 64 * 1024 * 1024,
      timeout: 60_000,
    });
    if (run.status !== 0 || !run.stdout?.trim()) {
      throw new Error(
        `The signup attestation did not run: ${run.stderr || run.error?.message || "no output"}`,
      );
    }
    token = run.stdout.trim();
  } finally {
    rmSync(dir, { recursive: true, force: true });
  }

  // 3. Redeem the token for a free-tier account + key.
  const grantResponse = await fetch(`${baseUrl}/v5/free-tier/grant`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(useCase ? { token, useCase } : { token }),
  });
  const decision = (await grantResponse.json().catch(() => ({}))) as {
    accepted?: boolean;
    apiKey?: string;
    accountId?: string;
    tier?: string;
    allocationBand?: string;
    grantedCredits?: number;
    guidance?: string;
    reasons?: string[];
  };
  if (!decision.accepted || !decision.apiKey || !decision.accountId) {
    const guidance = decision.guidance ? ` ${decision.guidance}` : "";
    const reasons = decision.reasons?.length ? ` (${decision.reasons.join("; ")})` : "";
    throw new Error(`Anonymous free tier was not granted.${guidance}${reasons}`);
  }
  return {
    apiKey: decision.apiKey,
    accountId: decision.accountId,
    tier: decision.tier ?? "free",
    allocationBand: decision.allocationBand,
    grantedCredits: decision.grantedCredits,
    guidance: decision.guidance,
  };
}

/**
 * Return the stored anonymous API key, creating (and persisting) an anonymous
 * account the first time. Used by the CLI's not-logged-in path so ordinary
 * commands "just work" without a login.
 */
export async function ensureAnonymousApiKey(baseUrl?: string): Promise<string> {
  const config = readConfig();
  if (config.anonymousApiKey) return config.anonymousApiKey;

  process.stderr.write("No Freestyle login found — creating an anonymous free-tier account…\n");
  const account = await createAnonymousAccount({ baseUrl });
  writeConfig({
    ...readConfig(),
    anonymousApiKey: account.apiKey,
    anonymousAccountId: account.accountId,
  });
  process.stderr.write(
    `Created anonymous account ${account.accountId}. It's yours to keep — run \`freestyle claim\` ` +
      `to attach it to a login.\n`,
  );
  return account.apiKey;
}
