// Page-local helpers for AdminImport (ported from React AdminImport.tsx).
// Behavior and env/localStorage keys preserved exactly.

export const CHUNK_SIZE = 5000; // rows per API call — reduced to avoid DB statement timeouts
export const UI_UPDATE_INTERVAL = 25000; // only update UI every N rows to reduce memory pressure
export const CHECKPOINT_INTERVAL = 50000; // save checkpoint every N rows
export const GC_PAUSE_INTERVAL = 100000; // pause to let browser GC every N rows

export interface ImportState {
  status: "idle" | "parsing" | "uploading" | "done" | "error" | "resume_prompt";
  fileName: string;
  totalRows: number;
  processedRows: number;
  insertedRows: number;
  errorRows: number;
  errorMessages: string[];
  resumeFrom: number; // rows to skip when resuming
  jobId: string | null; // DB import_jobs id for URL imports
}

export const initialState: ImportState = {
  status: "idle",
  fileName: "",
  totalRows: 0,
  processedRows: 0,
  insertedRows: 0,
  errorRows: 0,
  errorMessages: [],
  resumeFrom: 0,
  jobId: null,
};

export function getCheckpointKey(type: string) {
  return `import_checkpoint_${type}`;
}

export interface Checkpoint {
  fileName: string;
  fileSize: number;
  processedRows: number;
  insertedRows: number;
  timestamp: number;
}

export function saveCheckpoint(type: string, cp: Checkpoint) {
  try { localStorage.setItem(getCheckpointKey(type), JSON.stringify(cp)); } catch {}
}

export function loadCheckpoint(type: string): Checkpoint | null {
  try {
    const raw = localStorage.getItem(getCheckpointKey(type));
    return raw ? JSON.parse(raw) : null;
  } catch { return null; }
}

export function clearCheckpoint(type: string) {
  try { localStorage.removeItem(getCheckpointKey(type)); } catch {}
}

export function normalizeHeader(name: string): string {
  return name
    .toLowerCase()
    .normalize("NFD")
    .replace(/[̀-ͯ]/g, "") // Remove accents
    .replace(/[_\s]+/g, "_")
    .replace(/[^a-z0-9_]/g, "")
    .trim();
}

// Map of normalized header names to expected DB column names for fiber
export const FIBER_HEADER_MAP: Record<string, string> = {
  id_placemark: "id_placemark",
  idplacemark: "id_placemark",
  id_appart: "id_appart",
  idappart: "id_appart",
  uuidadresse: "uuidadresse",
  idgouvqc: "uuidadresse",
  id_gouv_qc: "uuidadresse",
  nom: "nom",
  civique: "civique",
  appartement: "appartement",
  appt: "appartement",
  apt: "appartement",
  rue: "rue",
  ville: "ville",
  code_postal: "code_postal",
  codepostal: "code_postal",
  cp: "code_postal",
  lien_googlemap: "lien_googlemap",
  liengooglemap: "lien_googlemap",
  googlemap: "lien_googlemap",
  zone_tarifaire: "zone_tarifaire",
  zonetarifaire: "zone_tarifaire",
  zone: "zone_tarifaire",
  max_speed: "max_speed",
  maxspeed: "max_speed",
  vitesse: "max_speed",
  vitesse_max: "max_speed",
  commentaire: "commentaire",
  commentaires: "commentaire",
  comment: "commentaire",
  lien_map_targo: "_skip",
  lienmaptargo: "_skip",
};

export function parseLine(line: string, delimiter: string): string[] {
  if (delimiter === "\t" || delimiter === ";") {
    return line.split(delimiter).map((v) => v.trim().replace(/^"|"$/g, ""));
  }
  // CSV with potential quoted fields
  const values: string[] = [];
  let current = "";
  let inQuotes = false;
  for (let i = 0; i < line.length; i++) {
    const char = line[i];
    if (char === '"') {
      if (inQuotes && i + 1 < line.length && line[i + 1] === '"') {
        current += '"';
        i++;
      } else {
        inQuotes = !inQuotes;
      }
    } else if (char === delimiter && !inQuotes) {
      values.push(current.trim());
      current = "";
    } else {
      current += char;
    }
  }
  values.push(current.trim());
  return values;
}
