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

/** Parse Apple .strings format: "key" = "value"; */
export const iosStringsConverter: FormatConverter = {
  parse(input: string): Record<string, string> {
    const result: Record<string, string> = {};
    // Match "key" = "value"; lines (also handles unquoted keys)
    const linePattern = /^\s*"((?:[^"\\]|\\.)*)"\s*=\s*"((?:[^"\\]|\\.)*)"\s*;/gm;
    let match: RegExpExecArray | null;

    while ((match = linePattern.exec(input)) !== null) {
      const key = match[1].replace(/\\"/g, '"').replace(/\\\\/g, "\\").replace(/\\n/g, "\n");
      const value = match[2].replace(/\\"/g, '"').replace(/\\\\/g, "\\").replace(/\\n/g, "\n");
      result[key] = value;
    }

    return result;
  },

  serialize(data: Record<string, string>): string {
    const escape = (s: string) =>
      s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");

    const entries = Object.entries(data)
      .map(([key, value]) => `"${escape(key)}" = "${escape(value)}";`)
      .join("\n");

    return `/* Generated by Better I18N Translation File Converter */\n\n${entries}\n`;
  },
};
