import { SITE_URL } from '../lib/schema.js';

const BASE_URL = process.env.TEST_URL || SITE_URL;

console.log(`\n🚀 Starting OG Image Verification for ${BASE_URL}\n`);

const routes = [
  '/de/opengraph-image',
  '/en/opengraph-image',
  '/de/blog/opengraph-image',
  '/de/api/og/product?slug=low-voltage-cables',
  '/en/api/og/product?slug=medium-voltage-cables',
];

async function verifyImage(path: string): Promise<boolean> {
  const url = `${BASE_URL}${path}`;
  const start = Date.now();

  try {
    const response = await fetch(url);
    const duration = Date.now() - start;

    console.log(`Checking ${url}...`);

    const body = await response.clone().text();
    const contentType = response.headers.get('content-type');

    if (response.status !== 200) {
      console.log(`  Headers: ${JSON.stringify(Object.fromEntries(response.headers))}`);
      console.log(`  Status Text: ${response.statusText}`);
      throw new Error(
        `Status: ${response.status}. Body preview: ${body.substring(0, 1000).replace(/\n/g, ' ')}...`,
      );
    }

    if (!contentType?.includes('image/png')) {
      throw new Error(
        `Content-Type: ${contentType}. Body preview: ${body.substring(0, 1000).replace(/\n/g, ' ')}...`,
      );
    }

    const buffer = await response.arrayBuffer();
    const bytes = new Uint8Array(buffer);

    // PNG Signature: 89 50 4E 47 0D 0A 1A 0A
    if (bytes[0] !== 0x89 || bytes[1] !== 0x50 || bytes[2] !== 0x4e || bytes[3] !== 0x47) {
      throw new Error('Invalid PNG signature');
    }

    if (bytes.length < 10000) {
      throw new Error(`Image too small (${bytes.length} bytes), likely blank`);
    }

    console.log(`  ✅ OK (${bytes.length} bytes, ${duration}ms)`);
    return true;
  } catch (error: unknown) {
    console.error(`  ❌ FAILED:`, error);
    return false;
  }
}

async function run() {
  let allOk = true;
  for (const route of routes) {
    const ok = await verifyImage(route);
    if (!ok) allOk = false;
  }

  if (allOk) {
    console.log('\n✨ All OG images verified successfully!\n');
    process.exit(0);
  } else {
    console.error('\n⚠️  Some OG images failed verification.\n');
    process.exit(1);
  }
}

run();
