/**
 * A snapshot of what a feedback directory actually contains, so the chart generator can be told
 * about the data rather than only about the schema.
 *
 * The schema context lists every member the cube *could* have. On its own that is what makes the
 * generator confidently wrong: asked to "filter to the website survey" it emits
 * `sourceName contains ["Website"]` for a source really called "Web widget prod", asks for
 * `npsScore` in a directory that has never held an NPS question, and renders an empty chart with no
 * error. Naming the real sources, questions and languages turns those into near-misses the model
 * can resolve itself.
 *
 * Everything here is pure so it can be unit-tested without a cube; `ai-data-profile.server.ts` runs
 * the queries and caches the result.
 */
import type { TChartQuery } from "@formbricks/types/analysis";

const CUBE_NAME = "FeedbackRecords";

export const SOURCE_NAME_DIMENSION_ID = `${CUBE_NAME}.sourceName`;
export const SOURCE_TYPE_DIMENSION_ID = `${CUBE_NAME}.sourceType`;
export const FIELD_LABEL_DIMENSION_ID = `${CUBE_NAME}.fieldLabel`;
export const FIELD_TYPE_DIMENSION_ID = `${CUBE_NAME}.fieldType`;
export const LANGUAGE_DIMENSION_ID = `${CUBE_NAME}.language`;
export const COLLECTED_AT_DIMENSION_ID = `${CUBE_NAME}.collectedAt`;
export const COUNT_MEASURE_ID = `${CUBE_NAME}.count`;

/**
 * How many distinct entries each list contributes to the prompt.
 *
 * Sized for usefulness, not completeness: the questions list is the one that changes answers most
 * often, so it gets the largest share. A directory past any of these caps is reported as truncated
 * rather than silently shortened — the model must not read a short list as proof a value is absent.
 */
export const AI_DATA_PROFILE_LIMITS = {
  sources: 40,
  questions: 100,
  languages: 25,
} as const;

export interface TAIDataProfileSource {
  name: string;
  type?: string;
}

export interface TAIDataProfileQuestion {
  label: string;
  fieldType?: string;
}

export interface TAIDataProfile {
  totalRecords: number;
  sources: TAIDataProfileSource[];
  questions: TAIDataProfileQuestion[];
  languages: string[];
  /** Field types present in the directory, which is what says whether NPS/CSAT/CES measures exist. */
  fieldTypes: string[];
  /** Earliest and latest month holding records, as `YYYY-MM`. Null when the directory is empty. */
  earliestMonth: string | null;
  latestMonth: string | null;
  truncated: {
    sources: boolean;
    questions: boolean;
    languages: boolean;
  };
}

/**
 * The four queries the profile is built from, each over-fetching by one row so a full page can be
 * reported as truncated without a second count query.
 */
export const buildDataProfileQueries = (): {
  sources: TChartQuery;
  questions: TChartQuery;
  languages: TChartQuery;
  timeline: TChartQuery;
} => ({
  sources: {
    dimensions: [SOURCE_NAME_DIMENSION_ID, SOURCE_TYPE_DIMENSION_ID],
    order: [
      [SOURCE_NAME_DIMENSION_ID, "asc"],
      [SOURCE_TYPE_DIMENSION_ID, "asc"],
    ],
    limit: AI_DATA_PROFILE_LIMITS.sources + 1,
  },
  questions: {
    dimensions: [FIELD_LABEL_DIMENSION_ID, FIELD_TYPE_DIMENSION_ID],
    order: [
      [FIELD_LABEL_DIMENSION_ID, "asc"],
      [FIELD_TYPE_DIMENSION_ID, "asc"],
    ],
    limit: AI_DATA_PROFILE_LIMITS.questions + 1,
  },
  languages: {
    dimensions: [LANGUAGE_DIMENSION_ID],
    order: [[LANGUAGE_DIMENSION_ID, "asc"]],
    limit: AI_DATA_PROFILE_LIMITS.languages + 1,
  },
  // Doubles as the volume query: the month buckets sum to the directory total, so the profile costs
  // four round trips rather than five.
  timeline: {
    measures: [COUNT_MEASURE_ID],
    timeDimensions: [{ dimension: COLLECTED_AT_DIMENSION_ID, granularity: "month" }],
    order: [[COLLECTED_AT_DIMENSION_ID, "asc"]],
  },
});

const toRows = (rows: unknown): Record<string, unknown>[] =>
  Array.isArray(rows)
    ? rows.filter((row): row is Record<string, unknown> => typeof row === "object" && row !== null)
    : [];

const readString = (row: Record<string, unknown>, key: string): string | undefined => {
  const raw = row[key];
  if (typeof raw !== "string") return undefined;
  const value = raw.trim();
  return value ? value : undefined;
};

const readNumber = (row: Record<string, unknown>, key: string): number => {
  const raw = row[key];
  if (typeof raw === "number") return Number.isFinite(raw) ? raw : 0;
  // Cube returns counts as strings on some drivers.
  if (typeof raw === "string") {
    const parsed = Number(raw);
    return Number.isFinite(parsed) ? parsed : 0;
  }
  return 0;
};

/**
 * Cube keys a granular time dimension as `<dimension>.<granularity>`, but has historically also
 * returned the bare dimension id. Both are read so a Cube upgrade cannot silently empty the
 * date range while every other part of the profile still looks right.
 */
const readMonth = (row: Record<string, unknown>): string | undefined => {
  const raw =
    readString(row, `${COLLECTED_AT_DIMENSION_ID}.month`) ?? readString(row, COLLECTED_AT_DIMENSION_ID);
  return raw?.slice(0, 7);
};

/** Distinct, trimmed values in row order, capped at `limit`, flagging whether rows were left over. */
const collectCapped = <T>(
  rows: Record<string, unknown>[],
  limit: number,
  toKey: (row: Record<string, unknown>) => string | undefined,
  toEntry: (row: Record<string, unknown>) => T
): { entries: T[]; truncated: boolean } => {
  const seen = new Set<string>();
  const entries: T[] = [];
  let truncated = false;

  for (const row of rows) {
    const key = toKey(row);
    if (key === undefined || seen.has(key)) continue;
    if (entries.length >= limit) {
      truncated = true;
      break;
    }
    seen.add(key);
    entries.push(toEntry(row));
  }

  return { entries, truncated };
};

export const collectDataProfile = ({
  sources,
  questions,
  languages,
  timeline,
}: {
  sources: unknown;
  questions: unknown;
  languages: unknown;
  timeline: unknown;
}): TAIDataProfile => {
  const sourceResult = collectCapped(
    toRows(sources),
    AI_DATA_PROFILE_LIMITS.sources,
    // Keyed on the pair: one source name can legitimately appear under two source types.
    (row) => {
      const name = readString(row, SOURCE_NAME_DIMENSION_ID);
      return name === undefined ? undefined : `${name} ${readString(row, SOURCE_TYPE_DIMENSION_ID) ?? ""}`;
    },
    (row) => ({
      name: readString(row, SOURCE_NAME_DIMENSION_ID) ?? "",
      ...(readString(row, SOURCE_TYPE_DIMENSION_ID) === undefined
        ? {}
        : { type: readString(row, SOURCE_TYPE_DIMENSION_ID) }),
    })
  );

  const questionResult = collectCapped(
    toRows(questions),
    AI_DATA_PROFILE_LIMITS.questions,
    // Keyed on the label alone: a question stored under two field types is still one question to
    // the person asking, and spending two of a hundred slots on it crowds out a real one.
    (row) => readString(row, FIELD_LABEL_DIMENSION_ID),
    (row) => ({
      label: readString(row, FIELD_LABEL_DIMENSION_ID) ?? "",
      ...(readString(row, FIELD_TYPE_DIMENSION_ID) === undefined
        ? {}
        : { fieldType: readString(row, FIELD_TYPE_DIMENSION_ID) }),
    })
  );

  const languageResult = collectCapped(
    toRows(languages),
    AI_DATA_PROFILE_LIMITS.languages,
    (row) => readString(row, LANGUAGE_DIMENSION_ID),
    (row) => readString(row, LANGUAGE_DIMENSION_ID) ?? ""
  );

  // Read off every question row rather than the capped list: which measures have data is a property
  // of the directory, and the closed field-type vocabulary is short enough that truncating the
  // question list must not truncate this.
  const fieldTypes = [
    ...new Set(
      toRows(questions)
        .map((row) => readString(row, FIELD_TYPE_DIMENSION_ID))
        .filter((value): value is string => value !== undefined)
    ),
  ].sort((a, b) => a.localeCompare(b));

  const timelineRows = toRows(timeline);
  const months = timelineRows
    .map(readMonth)
    .filter((month): month is string => month !== undefined)
    .sort((a, b) => a.localeCompare(b));

  return {
    totalRecords: timelineRows.reduce((total, row) => total + readNumber(row, COUNT_MEASURE_ID), 0),
    sources: sourceResult.entries,
    questions: questionResult.entries,
    languages: languageResult.entries,
    fieldTypes,
    earliestMonth: months[0] ?? null,
    latestMonth: months.at(-1) ?? null,
    truncated: {
      sources: sourceResult.truncated,
      questions: questionResult.truncated,
      languages: languageResult.truncated,
    },
  };
};

const formatList = (values: string[], truncated: boolean): string => {
  const lines = values.map((value) => `- ${value}`);
  if (truncated) {
    lines.push("- (list truncated — other values exist in this dataset)");
  }
  return lines.join("\n");
};

/**
 * Render the profile as the `## Data in this dataset` section of the system prompt.
 *
 * Returns an empty string for a profile that could not be built, so the caller can append it
 * unconditionally and fall back to schema-only generation.
 */
export const formatDataProfile = (profile: TAIDataProfile | null): string => {
  if (!profile) return "";

  if (profile.totalRecords === 0) {
    return `## Data in this dataset

This dataset holds no feedback records yet. Still answer the request with the query the user asked
for — it will simply return no rows — and do not invent filter values to make it look populated.`;
  }

  const sections: string[] = [
    `## Data in this dataset

These are the values actually stored in the dataset this query will run against. Use them.`,
    `### Volume
${profile.totalRecords} feedback records${
      profile.earliestMonth && profile.latestMonth
        ? `, collected between ${profile.earliestMonth} and ${profile.latestMonth}`
        : ""
    }.`,
  ];

  if (profile.sources.length > 0) {
    sections.push(
      `### Sources (\`${SOURCE_NAME_DIMENSION_ID}\`, with \`${SOURCE_TYPE_DIMENSION_ID}\`)
${formatList(
  profile.sources.map((source) => (source.type ? `${source.name} (${source.type})` : source.name)),
  profile.truncated.sources
)}`
    );
  }

  if (profile.questions.length > 0) {
    sections.push(
      `### Questions (\`${FIELD_LABEL_DIMENSION_ID}\`, with \`${FIELD_TYPE_DIMENSION_ID}\`)
${formatList(
  profile.questions.map((question) =>
    question.fieldType ? `${question.label} (${question.fieldType})` : question.label
  ),
  profile.truncated.questions
)}`
    );
  }

  if (profile.languages.length > 0) {
    sections.push(
      `### Languages (\`${LANGUAGE_DIMENSION_ID}\`)
${formatList(profile.languages, profile.truncated.languages)}`
    );
  }

  if (profile.fieldTypes.length > 0) {
    sections.push(
      `### Question types present
${profile.fieldTypes.join(", ")}`
    );
  }

  sections.push(`### Using this data
- Filter values must come from the lists above. If the user names something close to a listed value
  ("the website survey" for "Web widget prod"), use the listed value. If nothing is close and the
  list is not marked truncated, leave the filter out rather than inventing one — a query with no
  filter is a useful chart, a query filtered on a value that does not exist is an empty one.
- A measure whose question type is absent from "Question types present" has no data behind it. Do
  not answer with \`${CUBE_NAME}.npsScore\` where no \`nps\` question exists, nor with a CSAT or CES
  measure where no \`csat\` / \`ces\` question does; use \`${COUNT_MEASURE_ID}\` or the closest
  measure that is backed by data.
- The date range under Volume is context, not a filter to apply. "All time" means leaving the date
  range out altogether — pinning one to the dataset's current extent freezes the chart as new
  feedback arrives. A request for a period outside that range will legitimately return nothing.`);

  return sections.join("\n\n");
};
