import { google } from 'googleapis';
import { join } from 'path';
import {
    languageColumns,
} from './constants'
import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'fs';

const auth = new google.auth.GoogleAuth({
  keyFile: join(process.cwd(), 'cred.json'),
  scopes: ['https://www.googleapis.com/auth/spreadsheets.readonly'],
});

const sheets = google.sheets({ version: 'v4', auth });


function escapePoString(str: string): string {
  return (str || "").replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}

export default async function fetchSheet(spreadsheetId: string, outputDirs: string[]) {
  const sheetName = 'Project Strings'; // 你的 tab 名字
  const range = `${sheetName}!A1:ZZ`;  // 读取全部列
  const res = await sheets.spreadsheets.values.get({
    spreadsheetId,
    range,
  });

  const values = res.data.values;
  if (!values || values.length === 0) {
    console.error("❌ 没有数据");
    return;
  }

  const headers: string[] = values[0];
  const rows = values.slice(1);

  const headerIndexMap = Object.fromEntries(headers.map((h, i) => [h.trim(), i]));

  const files: Record<string, string[]> = {};
  for (const langCode of Object.values(languageColumns)) {
    files[langCode] = [];
  }

  for (const row of rows) {
    const key = row[headerIndexMap["key"]];
    if (!key) continue;

   for (const [columnName, langCode] of Object.entries(languageColumns)) {
      const colIndex = headerIndexMap[columnName];
      const val = colIndex != null ? row[colIndex] || "" : "";

      const msgid = `msgid "${escapePoString(key)}"`;
      const msgstr = `msgstr "${escapePoString(val)}"`;

      const prevLines = files[langCode];
      const needsLeadingNewline = prevLines.length > 0 && prevLines[prevLines.length - 1].trim() !== "";

      if (needsLeadingNewline) {
        prevLines.push(""); // 插入空行
      }

      prevLines.push(msgid);
      prevLines.push(msgstr);
    }
  }

  const poFileNames = ["strikingly.po", "sxl.po"];

    for (const [langCode, lines] of Object.entries(files)) {
      const newEntries = lines.join("\n");

      for (const baseDir of outputDirs) {
        for (const poFile of poFileNames) {
          const dir = join(baseDir, langCode);
          mkdirSync(dir, { recursive: true });
          const filePath = join(dir, poFile);

          let finalContent = "";

          if (existsSync(filePath)) {
            const raw = readFileSync(filePath, "utf-8");

            const currentKeys = new Set(
              lines.map((line) => {
                const match = line.match(/msgid\s+"(.*?)"/);
                return match?.[1] ?? "";
              }).filter(Boolean)
            );

            const segments: string[] = [];
            const linesArr = raw.split("\n");
            let buffer: string[] = [];

            for (let i = 0; i < linesArr.length; i++) {
              const line = linesArr[i];
              buffer.push(line);

              const nextLine = linesArr[i + 1];
              const isEndOfBlock = !nextLine || nextLine.trim() === "";

              if (isEndOfBlock) {
                segments.push(buffer.join("\n"));
                buffer = [];
                while (linesArr[i + 1]?.trim() === "") i++; // 跳过多余空行
              }
            }

            const retainedSegments = segments.filter((segment) => {
              const match = segment.match(/msgid\s+"(.*?)"/);
              const key = match?.[1];
              return !currentKeys.has(key ?? "");
            });

            finalContent = retainedSegments.join("\n\n").trim();
            const output = [finalContent, newEntries].filter(Boolean).join("\n\n") + "\n";
            writeFileSync(filePath, output, "utf-8");

            console.log(`✅ ${langCode}: 写入 ${filePath}，共 ${lines.length} 条`);
          }
        }
      }
    }
}
