import {
  issueMatrixText,
  type IssueMatrixLanguage,
} from "./components/issue-matrix-i18n";
import { issueMatrixExtraText } from "./components/issue-matrix-extra-i18n";
import { evaluationFormText } from "../../admin/evaluation-form/evaluation-form-i18n";
import { reportGridDefaults } from "../progress-report/progress-report-grid-labels";

export type IssueMatrixModule =
  | "pswg"
  | "ministry"
  | "cdc"
  | "cefp"
  | "cdcgpsf";
export function issueMatrixModuleFromPath(
  path: string,
): IssueMatrixModule | null {
  const segment = path.split("/")[1];
  if (segment === "cdc-gpsf") return "cdcgpsf";
  return ["pswg", "ministry", "cdc", "cefp"].includes(segment)
    ? (segment as IssueMatrixModule)
    : null;
}
export function issueMatrixDefaults(language: IssueMatrixLanguage) {
  return {
    ...issueMatrixText[language],
    ...issueMatrixExtraText[language],
    gridLocale: reportGridDefaults(language),
    evaluation: {
      ...evaluationFormText[language],
      actionsLabel:
        language === "en" ? "Evaluation actions" : "សកម្មភាពវាយតម្លៃ",
      notRated: language === "en" ? "Not rated" : "មិនទាន់វាយតម្លៃ",
    },
  };
}
export type IssueMatrixLabels = ReturnType<typeof issueMatrixDefaults>;
const keys: Record<string, string> = {
  title: "page_title",
  exportAsXlsx: "export_xlsx",
  noData: "no_data",
  totalIssues: "stats.total_issues",
  solved: "stats.solved",
  inProgress: "stats.in_progress",
  notAddressed: "stats.not_addressed",
  totalPrimaryAgencies: "stats.total_primary_agencies",
  "columns.id": "column.no",
  "columns.category": "column.issue_category",
  "columns.verificationLink": "column.link_to_verification_source",
  "detail.title": "detail.page_title",
};
export function issueMatrixTranslationKey(path: string) {
  return (
    keys[path] ??
    path
      .replace(/^columns\./, "column.")
      .replace(/^filters\./, "filter.")
      .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
      .replace(/ /g, "_")
      .toLowerCase()
  );
}
export function resolveIssueMatrixLabels(
  language: IssueMatrixLanguage,
  dictionary: Record<string, string>,
): IssueMatrixLabels {
  function visit(value: object, prefix = ""): object {
    return Object.fromEntries(
      Object.entries(value).map(([key, fallback]) => {
        const path = prefix ? prefix + "." + key : key;
        const translated = dictionary[issueMatrixTranslationKey(path)];
        return [
          key,
          typeof fallback === "string"
            ? typeof translated === "string" && translated.trim()
              ? translated
              : fallback
            : visit(fallback, path),
        ];
      }),
    );
  }
  return visit(issueMatrixDefaults(language)) as IssueMatrixLabels;
}
export async function fetchIssueMatrixDictionary(
  module: IssueMatrixModule,
  language: IssueMatrixLanguage,
  signal?: AbortSignal,
  page = "issue_matrix",
) {
  const base = (
    process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001/api/v1"
  ).replace(/\/$/, "");
  const query = new URLSearchParams({
    module,
    page,
    language: language === "kh" ? "km" : "en",
  });
  const response = await fetch(base + "/translations/dictionary?" + query, {
    credentials: "include",
    cache: "no-store",
    signal,
  });
  if (!response.ok) throw new Error("Could not load issue matrix translations");
  let value: unknown = await response.json();
  for (
    let depth = 0;
    depth < 5 && value && typeof value === "object";
    depth++
  ) {
    const record = value as Record<string, unknown>;
    if (record.translations && typeof record.translations === "object") {
      return Object.fromEntries(
        Object.entries(record.translations).filter(
          (entry): entry is [string, string] =>
            typeof entry[1] === "string" && !!entry[1].trim(),
        ),
      );
    }
    value = record.data;
  }
  return {};
}
