import fs from "fs";
import path from "path";
import dotenv from "dotenv";
import { createClient } from "@supabase/supabase-js";

dotenv.config();

const SUPABASE_URL = process.env.SUPABASE_URL || "";
const SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY || "";
const MARKET = process.env.SYNC_SEED_MARKET || "BE-WAL";
const SEED_PATH = process.env.SYNC_SEED_PATH || path.join(process.cwd(), "out", "seed_companies.sql");

if (!SUPABASE_URL || !SUPABASE_SERVICE_ROLE_KEY) {
  console.error("Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in .env");
  process.exit(1);
}

if (!fs.existsSync(SEED_PATH)) {
  console.error(`Seed file not found: ${SEED_PATH}`);
  process.exit(1);
}

const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, { auth: { persistSession: false } });

function sqlQuote(s) {
  return `'${String(s).replace(/'/g, "''")}'`;
}

async function fetchLogoMap() {
  let from = 0;
  const step = 500;
  const map = new Map();

  while (true) {
    const { data, error } = await supabase
      .from("companies")
      .select("slug, logo_url, market")
      .eq("market", MARKET)
      .range(from, from + step - 1)
      .order("slug", { ascending: true });

    if (error) throw error;
    if (!data || !data.length) break;

    for (const r of data) {
      if (r?.slug && r?.logo_url) map.set(String(r.slug), String(r.logo_url));
    }

    from += data.length;
    if (data.length < step) break;
  }

  return map;
}

async function main() {
  const logoMap = await fetchLogoMap();
  console.log(`[SyncSeedLogos] DB logos loaded: ${logoMap.size}`);

  const src = fs.readFileSync(SEED_PATH, "utf-8");

  // Match one INSERT payload and capture slug + logo/cover tuple region.
  const re = /SELECT\s+'([^']+)'.*?,\s*(\d+)\s*,\s*(NULL|'https?:\/\/[^']+')\s*,\s*(NULL|'https?:\/\/[^']+')\s*,\s*ARRAY\[/gs;
  let seen = 0;
  let updated = 0;

  const out = src.replace(re, (m, slug, ras, logoToken, coverToken) => {
    seen += 1;
    const dbLogo = logoMap.get(String(slug));
    if (!dbLogo) return m;
    const newLogo = sqlQuote(dbLogo);
    if (logoToken === newLogo) return m;
    updated += 1;
    return m.replace(`${ras}, ${logoToken}, ${coverToken}, ARRAY[`, `${ras}, ${newLogo}, ${coverToken}, ARRAY[`);
  });

  fs.writeFileSync(SEED_PATH, out, "utf-8");
  console.log(`[SyncSeedLogos] statements seen=${seen} updated=${updated} file=${SEED_PATH}`);
}

main().catch((e) => {
  console.error("Fatal:", e);
  process.exit(1);
});

