import { config } from "dotenv";
import path from "node:path";
import { promises as fs } from "node:fs";
import { createHash } from "node:crypto";

config({ path: path.resolve(process.cwd(), ".env.local") });
config({ path: path.resolve(process.cwd(), ".env") });

const IMAGE_EXTS = new Set([".jpg", ".jpeg", ".png", ".webp", ".gif", ".svg"]);

function guessMime(ext: string): string {
  const e = ext.toLowerCase();
  if (e === ".jpg" || e === ".jpeg") return "image/jpeg";
  if (e === ".png") return "image/png";
  if (e === ".webp") return "image/webp";
  if (e === ".gif") return "image/gif";
  if (e === ".svg") return "image/svg+xml";
  return "application/octet-stream";
}

async function walk(dir: string): Promise<string[]> {
  const out: string[] = [];
  let entries;
  try {
    entries = await fs.readdir(dir, { withFileTypes: true });
  } catch {
    return out;
  }
  for (const e of entries) {
    const full = path.join(dir, e.name);
    if (e.isDirectory()) out.push(...(await walk(full)));
    else if (IMAGE_EXTS.has(path.extname(e.name).toLowerCase())) out.push(full);
  }
  return out;
}

async function main() {
  if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL not set");

  const postgres = (await import("postgres")).default;
  const { drizzle } = await import("drizzle-orm/postgres-js");
  const { eq } = await import("drizzle-orm");
  const schema = await import("../src/lib/db/schema");

  const sql = postgres(process.env.DATABASE_URL!, { max: 1 });
  const db = drizzle(sql, { schema });

  const root = path.join(process.cwd(), "public", "uploads");
  const files = await walk(root);
  let inserted = 0;
  for (const abs of files) {
    const rel = abs
      .slice(path.join(process.cwd(), "public").length)
      .replace(/\\/g, "/");
    const existing = await db
      .select({ id: schema.mediaAssets.id })
      .from(schema.mediaAssets)
      .where(eq(schema.mediaAssets.path, rel))
      .limit(1);
    if (existing.length > 0) continue;
    try {
      const stat = await fs.stat(abs);
      const buf = await fs.readFile(abs);
      const sha256 = createHash("sha256").update(buf).digest("hex");
      await db
        .insert(schema.mediaAssets)
        .values({
          path: rel,
          originalName: path.basename(rel),
          mimeType: guessMime(path.extname(rel)),
          fileSize: stat.size,
          sha256,
        })
        .onConflictDoNothing({ target: schema.mediaAssets.path });
      inserted += 1;
    } catch (err) {
      console.error("[seed-media] failed for", rel, err);
    }
  }
  console.log(`Seeded ${inserted}/${files.length} media assets from public/uploads.`);
  await sql.end();
}

main()
  .then(() => process.exit(0))
  .catch((err) => {
    console.error(err);
    process.exit(1);
  });
