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

/** Parse gettext PO file — extracts msgid/msgstr pairs */
export const poConverter: FormatConverter = {
  parse(input: string): Record<string, string> {
    const result: Record<string, string> = {};
    const blocks = input.split(/\n\n+/);

    for (const block of blocks) {
      const msgidMatch = block.match(/^msgid\s+"((?:[^"\\]|\\.)*)"\s*$/m);
      const msgstrMatch = block.match(/^msgstr\s+"((?:[^"\\]|\\.)*)"\s*$/m);

      if (msgidMatch && msgstrMatch) {
        const key = msgidMatch[1].replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
        const value = msgstrMatch[1].replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
        if (key) {
          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 header = `# Translation file
# Generated by Better I18N Translation File Converter
msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
`;

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

    return `${header}\n${entries}\n`;
  },
};
