import { createId } from "@paralleldrive/cuid2";
import { readFileSync, writeFileSync } from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { generateObject } from "@formbricks/ai";
import { env } from "@/lib/env";
import { checkImportDraft } from "@/modules/survey/import/core/final-gate";
import {
  IMPORTABLE_QSF_FIXTURES,
  loadQsfFixture,
} from "@/modules/survey/import/qsf/__fixtures__/load-fixture";
import type { TQsfPlanGenerate } from "@/modules/survey/import/qsf/ai-plan";
import { runQsfImport } from "@/modules/survey/import/qsf/pipeline";
import { prepareQsfImport } from "@/modules/survey/import/qsf/prepare";

/**
 * ENG-3654 — the Qualtrics import against a real model. Not run in CI: CI uses the recorded plans in
 * `modules/survey/import/qsf/__fixtures__/plans/` with the AI mocked.
 *
 *   pnpm qsf:eval                          every fixture, once
 *   pnpm qsf:eval --fixture=large-150      one fixture
 *   pnpm qsf:eval --runs=3                 each fixture three times, for latency spread
 *   pnpm qsf:eval --record                 also rewrite the fixtures' recorded plans from the model,
 *                                          except the hand-made hostile, injection and pollution ones
 *   pnpm qsf:eval --record --record-dir=/tmp/plans
 *                                          record into another directory, leaving the fixtures alone
 *   pnpm qsf:eval --file=/path/to/x.qsf    a local file; never recorded
 *
 * It runs the real pipeline — reader, sanitizer, chunking, checks, retry, assembly and the final
 * gate — with the model call built from the validated environment (`AI_PROVIDER`, `AI_MODEL` and the
 * provider's credentials, from `.env`), so it needs no organization and no license. Credentials are
 * read from the environment only. A redirect in a file asks `getExternalUrlsPermission`, which on
 * Cloud reads billing; the fixtures' redirects need no database off Cloud.
 *
 * What it reports per run: duration, AI calls, input and output tokens, output tokens per question
 * (what chunk sizing rests on), whether the draft passes the create's checks, and the report's issue
 * codes. Never the file's text: a `--file` may be a customer's survey, and its recorded plan would
 * paraphrase it in logic notes, which is why `--file` never records.
 */

const FIXTURE_DIR = join(
  dirname(fileURLToPath(import.meta.url)),
  "../modules/survey/import/qsf/__fixtures__"
);
const DEADLINE_MS = 120_000;

/**
 * Plans `--record` never rewrites. The hostile plan has no fixture of its own and is written by hand;
 * the injection and pollution plans are hand-authored to play a model that went wrong, and a
 * well-behaved model's answer would quietly turn their tests into tests of nothing.
 */
const NEVER_RECORDED: ReadonlySet<string> = new Set(["hostile", "prompt-injection", "pollution"]);

interface TArgs {
  fixtures: string[];
  file: string | null;
  runs: number;
  record: boolean;
  /** Where `--record` writes: the fixtures' plans, unless `--record-dir` names another directory. */
  recordDir: string;
}

const parseArgs = (argv: ReadonlyArray<string>): TArgs => {
  const options = new Map(
    argv
      .filter((arg) => arg.startsWith("--"))
      .map((arg) => {
        const [key, value] = arg.slice(2).split("=", 2);
        return [key, value ?? "true"] as const;
      })
  );
  const fixture = options.get("fixture");
  const runs = Number(options.get("runs") ?? "1");
  return {
    fixtures: fixture
      ? [fixture.endsWith(".qsf") ? fixture : `${fixture}.qsf`]
      : [...IMPORTABLE_QSF_FIXTURES],
    file: options.get("file") ?? null,
    runs: Number.isSafeInteger(runs) && runs > 0 ? runs : 1,
    record: options.get("record") === "true",
    recordDir: resolve(options.get("record-dir") ?? join(FIXTURE_DIR, "plans")),
  };
};

/** The model call, from the environment rather than an organization's settings. */
const environmentGenerate =
  (onResponse: (object: unknown) => void): TQsfPlanGenerate =>
  async (request) => {
    const result = await generateObject(request, env);
    onResponse(result.object);
    return result;
  };

interface TRecordedPlan {
  questions: { ref?: unknown }[];
  skipped: unknown[];
  pages: unknown[];
}

/** One plan from every answer of a run, a question's last answer winning (the retry's). */
const mergeResponses = (responses: unknown[]): TRecordedPlan => {
  const questions = new Map<unknown, { ref?: unknown }>();
  const plan: TRecordedPlan = { questions: [], skipped: [], pages: [] };
  for (const response of responses) {
    const object = response as Partial<TRecordedPlan>;
    plan.pages.push(...(object.pages ?? []));
    plan.skipped.push(...(object.skipped ?? []));
    for (const question of object.questions ?? []) questions.set(question.ref, question);
  }
  plan.questions = [...questions.values()];
  return plan;
};

/** One run of one survey; its merged plan written into `recordDir` when that is set. */
const runOnce = async (name: string, qsf: Record<string, unknown>, recordDir: string | null) => {
  const responses: unknown[] = [];
  const startedAt = performance.now();
  const prepared = prepareQsfImport(qsf, name);
  const result = await runQsfImport({
    prepared,
    workspaceId: createId(),
    organizationId: "qsf-eval",
    userId: null,
    signal: AbortSignal.timeout(DEADLINE_MS),
    deadlineMs: DEADLINE_MS,
    onProgress: () => undefined,
    generate: environmentGenerate((object) => responses.push(object)),
  });
  const durationMs = Math.round(performance.now() - startedAt);
  const questions = result.report.summary.questions;
  const outputTokens = result.usage?.outputTokens ?? 0;

  if (recordDir !== null) {
    const path = join(recordDir, `${basename(name, ".qsf")}.plan.json`);
    const recording = {
      source: "recorded",
      model: env.AI_MODEL ?? null,
      provider: env.AI_PROVIDER ?? null,
      recordedAt: new Date().toISOString(),
    };
    writeFileSync(path, `${JSON.stringify({ recording, plan: mergeResponses(responses) }, null, 2)}\n`);
  }

  return {
    fixture: name,
    durationMs,
    calls: responses.length,
    questionsIn: prepared.survey.questions.size,
    questionsOut: questions,
    inputTokens: result.usage?.inputTokens ?? 0,
    outputTokens,
    outputTokensPerQuestion: questions > 0 ? Math.round(outputTokens / questions) : null,
    passesCreateCheck: checkImportDraft(result.payload).length === 0,
    issues: result.report.issues.map((issue) => issue.code).sort((left, right) => left.localeCompare(right)),
  };
};

interface TSource {
  name: string;
  qsf: Record<string, unknown>;
  recordable: boolean;
}

/** What to import: the `--file`, or the fixtures, each with whether `--record` may rewrite its plan. */
const loadSources = (args: TArgs): TSource[] =>
  args.file
    ? [
        {
          name: basename(args.file),
          qsf: JSON.parse(readFileSync(resolve(args.file), "utf8")) as Record<string, unknown>,
          recordable: false,
        },
      ]
    : args.fixtures.map((name) => ({
        name,
        qsf: loadQsfFixture(name),
        recordable: !NEVER_RECORDED.has(basename(name, ".qsf")),
      }));

/** Say which plans `--record` leaves alone, and why. */
const explainRecording = (args: TArgs, sources: readonly TSource[]): void => {
  if (!args.record) return;
  if (args.file) {
    console.log("--record is ignored for --file: a recorded plan would paraphrase the file.");
    return;
  }
  for (const source of sources) {
    if (!source.recordable) console.log(`--record leaves ${source.name}'s plan as it is.`);
  }
};

/** One run, printed as a line of JSON: its summary, or the error's name and nothing else. */
const printRun = async (source: TSource, run: number, recordDir: string | null): Promise<void> => {
  try {
    const summary = await runOnce(source.name, source.qsf, recordDir);
    console.log(JSON.stringify({ run, ...summary }));
  } catch (error) {
    // The name and nothing else: a provider's message can quote the prompt.
    console.log(
      JSON.stringify({ run, fixture: source.name, failed: error instanceof Error ? error.name : "unknown" })
    );
    process.exitCode = 1;
  }
};

const evaluate = async () => {
  const args = parseArgs(process.argv.slice(2));
  const sources = loadSources(args);
  explainRecording(args, sources);

  // One run at a time, by design: runs side by side would share the provider's rate limit and skew
  // the latencies this script is for.
  for (const source of sources) {
    for (let run = 1; run <= args.runs; run++) {
      const record = args.record && source.recordable && run === 1;
      await printRun(source, run, record ? args.recordDir : null); // NOSONAR(typescript:S9382) -- runs are sequential on purpose
    }
  }
};

/**
 * The eval. Run through `run-esm-script.mts` (`pnpm qsf:eval`), which loads the app as ES modules —
 * `tsx` alone loads it as CommonJS, which cannot load `@formbricks/ai` — and awaits this; nothing runs
 * on import.
 */
export const main = async (): Promise<void> => {
  try {
    await evaluate();
  } catch (error) {
    console.error(error instanceof Error ? error.name : "unknown");
    process.exitCode = 1;
  }
};
