/**
 * NAS / network storage path mappings.
 *
 * The office NAS (\\newamun  /  10.10.10.10) exposes several shares.
 * Windows maps these to drive letters.  This config lets us normalise
 * user-pasted paths to UNC and back, and build clickable `file:///` links.
 *
 * Fallback strategy:  hostname → IP.
 * If DNS fails to resolve `newamun`, every helper has an `...ByIp()` variant
 * that substitutes the hostname with the raw IP address.
 */

export interface NasDriveMapping {
  /** Drive letter (upper-case, no colon) */
  drive: string;
  /** UNC prefix WITHOUT trailing backslash, e.g. \\\\newamun\\Proiecte */
  unc: string;
  /** Human-readable label */
  label: string;
}

/** NAS hostname / IP */
export const NAS_HOST = "newamun";
export const NAS_IP = "10.10.10.10";

/** All known drive-letter → UNC mappings */
export const NAS_DRIVE_MAPPINGS: NasDriveMapping[] = [
  { drive: "A", unc: `\\\\${NAS_HOST}\\Arhiva`, label: "Arhiva" },
  { drive: "O", unc: `\\\\${NAS_HOST}\\Organizare`, label: "Organizare" },
  { drive: "P", unc: `\\\\${NAS_HOST}\\Proiecte`, label: "Proiecte" },
  { drive: "T", unc: `\\\\${NAS_HOST}\\Transfer`, label: "Transfer" },
];

// ── helpers ──

/**
 * Detect whether a string looks like a Windows network / mapped-drive path.
 * Accepts: `P:\folder\file.pdf`, `\\newamun\Proiecte\...`, `\\10.10.10.10\...`
 */
export function isNetworkPath(input: string): boolean {
  const trimmed = input.trim();
  // UNC path (hostname or IP)
  if (trimmed.startsWith("\\\\")) return true;
  // Mapped drive letter that we recognise
  const match = trimmed.match(/^([A-Z]):\\/i);
  if (match) {
    const letter = match[1]!.toUpperCase();
    return NAS_DRIVE_MAPPINGS.some((m) => m.drive === letter);
  }
  return false;
}

/**
 * Normalise to UNC path using hostname (replace drive letter with \\newamun\Share).
 * If already UNC or unrecognised → returns the original trimmed.
 */
export function toUncPath(input: string): string {
  const trimmed = input.trim();
  if (trimmed.startsWith("\\\\")) return trimmed;
  const match = trimmed.match(/^([A-Z]):(\\.*)/i);
  if (match) {
    const letter = match[1]!.toUpperCase();
    const rest = match[2]!;
    const mapping = NAS_DRIVE_MAPPINGS.find((m) => m.drive === letter);
    if (mapping) return `${mapping.unc}${rest}`;
  }
  return trimmed;
}

/**
 * Swap hostname → IP in a UNC path.
 * `\\newamun\Proiecte\file.pdf` → `\\10.10.10.10\Proiecte\file.pdf`
 * Already-IP or unrecognised paths are returned unchanged.
 */
export function toUncPathByIp(input: string): string {
  const unc = toUncPath(input);
  const hostPrefix = `\\\\${NAS_HOST}\\`;
  if (unc.toLowerCase().startsWith(hostPrefix.toLowerCase())) {
    return `\\\\${NAS_IP}\\${unc.slice(hostPrefix.length)}`;
  }
  return unc;
}

/**
 * Build a clickable `file:///` URL from a UNC or drive-letter path.
 * Uses hostname by default.
 */
export function toFileUrl(input: string): string {
  const unc = toUncPath(input);
  const slashed = unc.replace(/\\/g, "/");
  return `file:///${slashed}`;
}

/**
 * Build a clickable `file:///` URL using the IP fallback.
 * Use when DNS fails to resolve hostname.
 */
export function toFileUrlByIp(input: string): string {
  const unc = toUncPathByIp(input);
  const slashed = unc.replace(/\\/g, "/");
  return `file:///${slashed}`;
}

/**
 * Extract a short display name from a full path.
 * e.g.  `\\newamun\Proiecte\095\doc.pdf`  →  `doc.pdf`
 */
export function pathFileName(input: string): string {
  const trimmed = input.trim();
  const parts = trimmed.split(/[\\/]/);
  return parts[parts.length - 1] || trimmed;
}

/**
 * Extract a short display path (share + last 2 segments).
 * e.g. `\\newamun\Proiecte\095 - 2020\99_DOC\file.pdf` → `Proiecte\…\99_DOC\file.pdf`
 */
export function shortDisplayPath(input: string): string {
  const unc = toUncPath(input);
  const parts = unc.replace(/^\\\\/, "").split("\\").filter(Boolean);
  // parts: [server, share, folder1, folder2, ..., file]
  if (parts.length <= 3) return parts.slice(1).join("\\");
  const share = parts[1] ?? "";
  const last2 = parts.slice(-2).join("\\");
  return `${share}\\…\\${last2}`;
}

/**
 * Return the human-readable label of the share a path belongs to.
 * e.g. `P:\095\file.pdf` → `Proiecte`
 */
export function shareLabelFor(input: string): string | undefined {
  const unc = toUncPath(input).toLowerCase();
  for (const m of NAS_DRIVE_MAPPINGS) {
    if (unc.startsWith(m.unc.toLowerCase())) return m.label;
  }
  return undefined;
}
