import type { FormatConverter } from "./types";

/** Parse Java .properties file — handles key=value and key: value */
export const propertiesConverter: FormatConverter = {
  parse(input: string): Record<string, string> {
    const result: Record<string, string> = {};
    const lines = input.split(/\r?\n/);
    let continuationValue = "";
    let continuationKey = "";

    for (const line of lines) {
      // Handle line continuation
      if (continuationKey) {
        const trimmed = line.trimStart();
        if (trimmed.endsWith("\\")) {
          continuationValue += trimmed.slice(0, -1);
        } else {
          result[continuationKey] = continuationValue + trimmed;
          continuationKey = "";
          continuationValue = "";
        }
        continue;
      }

      const trimmed = line.trim();
      // Skip comments and empty lines
      if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith("!")) continue;

      // Find separator (= or :)
      const eqIdx = trimmed.indexOf("=");
      const colonIdx = trimmed.indexOf(":");
      let sepIdx: number;

      if (eqIdx === -1 && colonIdx === -1) continue;
      if (eqIdx === -1) sepIdx = colonIdx;
      else if (colonIdx === -1) sepIdx = eqIdx;
      else sepIdx = Math.min(eqIdx, colonIdx);

      const key = trimmed.slice(0, sepIdx).trim();
      const value = trimmed.slice(sepIdx + 1).trim();

      if (!key) continue;

      // Handle line continuation
      if (value.endsWith("\\")) {
        continuationKey = key;
        continuationValue = value.slice(0, -1);
      } else {
        // Unescape unicode sequences
        result[key] = value.replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) =>
          String.fromCharCode(parseInt(hex, 16)),
        );
      }
    }

    return result;
  },

  serialize(data: Record<string, string>): string {
    const lines = ["# Generated by Better I18N Translation File Converter", ""];

    for (const [key, value] of Object.entries(data)) {
      // Escape special characters in key
      const escapedKey = key
        .replace(/\\/g, "\\\\")
        .replace(/\s/g, "\\ ")
        .replace(/=/g, "\\=")
        .replace(/:/g, "\\:");
      // Escape value (newlines, unicode if needed)
      const escapedValue = value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
      lines.push(`${escapedKey}=${escapedValue}`);
    }

    return lines.join("\n") + "\n";
  },
};
