import { config } from 'dotenv';
import * as fs from 'fs';
import { db } from '../lib/db';
import { homepageContent } from '../shared/schema';

// Load .env.local
config({ path: '.env.local' });

const NEW_SITE_ID = process.env.SITE_ID || process.env.RANKTRACTION_SITE_ID;

if (!NEW_SITE_ID) {
  console.error('Missing SITE_ID in .env.local');
  process.exit(1);
}

async function main() {
  if (!fs.existsSync('cms-seed-data.json')) {
    console.error('cms-seed-data.json not found. Run export-cms.ts first.');
    process.exit(1);
  }

  const rawData = fs.readFileSync('cms-seed-data.json', 'utf-8');
  const rows: any[] = JSON.parse(rawData);

  if (rows.length === 0) {
    console.log('No rows to seed.');
    return;
  }

  // Auto-detect old site ID: it's the shortest site_id in the exported data (which is the homepage)
  // or the part before the first dash if there's no homepage.
  let oldSiteId = rows.reduce((acc, row) => 
    row.site_id.length < acc.length ? row.site_id : acc
  , rows[0].site_id);
  
  // If the shortest one still has a path (e.g. oldsite.com-/about-us), strip it to find the base.
  // We assume the base site ID does not contain the path part.
  const oldSiteIdMatch = oldSiteId.match(/^(.*?)(-\/.*)?$/);
  if (oldSiteIdMatch && oldSiteIdMatch[1]) {
    oldSiteId = oldSiteIdMatch[1];
  }

  console.log(`Detected old base site ID: ${oldSiteId}`);
  console.log(`New base site ID: ${NEW_SITE_ID}`);

  let successCount = 0;

  for (const row of rows) {
    // Replace old base site ID with new base site ID
    const newRowSiteId = row.site_id.replace(oldSiteId, NEW_SITE_ID);
    
    try {
      await db.insert(homepageContent)
        .values({
          siteId: newRowSiteId,
          content: row.content,
          draftContent: row.draft_content,
          updatedAt: row.updated_at ? new Date(row.updated_at) : new Date(),
          updatedBy: row.updated_by
        })
        .onConflictDoUpdate({
          target: homepageContent.siteId,
          set: {
            content: row.content,
            draftContent: row.draft_content,
            updatedAt: row.updated_at ? new Date(row.updated_at) : new Date(),
            updatedBy: row.updated_by
          }
        });
      console.log(`Seeded: ${newRowSiteId}`);
      successCount++;
    } catch (error) {
      console.error(`Failed to seed ${newRowSiteId}:`, error);
    }
  }

  console.log(`Successfully seeded ${successCount} / ${rows.length} rows.`);
  process.exit(0);
}

main();
