/**
 * Seed static pages into page_layout_pointers + page_layouts.
 * Run: pnpm db:seed:pages
 * Requires: DATABASE_URL
 * Optional: ANTHROPIC_API_KEY (if absent, uses hardcoded placeholder content for accessibility + contact)
 */

import { scriptOutput } from '../../lib/script-output.js';
import { eq } from 'drizzle-orm';
import { readFileSync, readdirSync, existsSync } from 'fs';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import { marked } from 'marked';
import matter from 'gray-matter';
import { getDb } from '../client.js';
import { pageLayoutPointers } from '../schema.js';
import { createLivePointer } from '../queries/page-layout-pointers.js';
import { insertPageLayoutSeedRow } from '../queries/seed-page-layouts.js';
import { readOptionalAnthropicApiKey, readSeedDatabaseUrl } from '../seed-cli-env.js';

const __dirname = dirname(fileURLToPath(import.meta.url));
const CONTENT_DIR = resolve(__dirname, '../../../content');

type LocalizedText = { he: string; en: string };

interface PageSeed {
  slug: string;
  layoutId: string;
  heroId: string;
  contentId: string;
  heroTitle: LocalizedText;
  heroSubtitle: LocalizedText;
  body: LocalizedText;
}

const IDS: Record<string, { layout: string; hero: string; content: string }> = {
  about: {
    layout: '00000000-0000-4000-9000-000000000001',
    hero: '00000000-0000-4000-9001-000000000001',
    content: '00000000-0000-4000-9002-000000000001',
  },
  faq: {
    layout: '00000000-0000-4000-9000-000000000002',
    hero: '00000000-0000-4000-9001-000000000002',
    content: '00000000-0000-4000-9002-000000000002',
  },
  'legal/privacy': {
    layout: '00000000-0000-4000-9000-000000000003',
    hero: '00000000-0000-4000-9001-000000000003',
    content: '00000000-0000-4000-9002-000000000003',
  },
  'legal/terms': {
    layout: '00000000-0000-4000-9000-000000000004',
    hero: '00000000-0000-4000-9001-000000000004',
    content: '00000000-0000-4000-9002-000000000004',
  },
  'legal/tos-vendor': {
    layout: '00000000-0000-4000-9000-000000000005',
    hero: '00000000-0000-4000-9001-000000000005',
    content: '00000000-0000-4000-9002-000000000005',
  },
  'legal/vouchers': {
    layout: '00000000-0000-4000-9000-000000000006',
    hero: '00000000-0000-4000-9001-000000000006',
    content: '00000000-0000-4000-9002-000000000006',
  },
  'legal/cookies': {
    layout: '00000000-0000-4000-9000-000000000007',
    hero: '00000000-0000-4000-9001-000000000007',
    content: '00000000-0000-4000-9002-000000000007',
  },
  accessibility: {
    layout: '00000000-0000-4000-9000-000000000008',
    hero: '00000000-0000-4000-9001-000000000008',
    content: '00000000-0000-4000-9002-000000000008',
  },
  contact: {
    layout: '00000000-0000-4000-9000-000000000009',
    hero: '00000000-0000-4000-9001-000000000009',
    content: '00000000-0000-4000-9002-000000000009',
  },
};

function readMd(path: string): { title: string; html: string } {
  const parsed = matter(readFileSync(path, 'utf-8'));
  return {
    title: (parsed.data.title as string) ?? '',
    html: marked.parse(parsed.content) as string,
  };
}

function safeReadMd(path: string): { title: string; html: string } {
  if (!existsSync(path)) return { title: '', html: '' };
  return readMd(path);
}

function combineFaq(locale: string): string {
  const faqDir = resolve(CONTENT_DIR, 'faq');
  if (!existsSync(faqDir)) return '';
  return readdirSync(faqDir)
    .filter((f) => f.endsWith(`.${locale}.md`))
    .sort()
    .map((f) => {
      const parsed = matter(readFileSync(resolve(faqDir, f), 'utf-8'));
      const q = parsed.data.question as string;
      const a = marked.parse(parsed.content) as string;
      return `<h2>${q}</h2>${a}`;
    })
    .join('\n');
}

// Static placeholder content for pages that previously required AI generation.
// Replace with real content by setting proper markdown files or re-running with ANTHROPIC_API_KEY.
const PLACEHOLDERS = {
  a11yHe: `<h2>הצהרת נגישות</h2>
<p>מולטידיל מחויבת לנגישות דיגיטלית בהתאם לתקן IS 5568 ו-WCAG 2.1 AA.</p>
<h2>מה אנחנו עושים</h2>
<ul>
<li>האתר מותאם לשימוש עם קורא מסך</li>
<li>כל התמונות כוללות טקסט חלופי</li>
<li>ניתן לנווט באמצעות מקלדת בלבד</li>
<li>יחס ניגודיות עומד בדרישות AA</li>
</ul>
<h2>יצירת קשר בנושא נגישות</h2>
<p>לפניות בנושא נגישות: <strong>accessibility@multideal.co.il</strong></p>
<p>ביקורת נגישות אחרונה: אפריל 2026</p>`,

  a11yEn: `<h2>Accessibility Statement</h2>
<p>Multideal is committed to digital accessibility in accordance with IS 5568 and WCAG 2.1 AA.</p>
<h2>What We Do</h2>
<ul>
<li>Site is compatible with screen readers</li>
<li>All images include alternative text</li>
<li>Full keyboard navigation supported</li>
<li>Color contrast meets AA requirements</li>
</ul>
<h2>Accessibility Contact</h2>
<p>For accessibility inquiries: <strong>accessibility@multideal.co.il</strong></p>
<p>Last accessibility audit: April 2026</p>`,

  contactHe: `<p>ברוכים הבאים לעמוד יצירת הקשר של מולטידיל. אנחנו כאן לעזור!</p>
<ul>
<li><strong>אימייל:</strong> support@multideal.co.il</li>
<li><strong>שעות פעילות:</strong> ראשון–חמישי, 9:00–18:00</li>
<li><strong>זמן תגובה:</strong> עד 2 ימי עסקים</li>
<li><strong>פניות דחופות:</strong> <a href="https://wa.me/972500000000">WhatsApp</a></li>
</ul>`,

  contactEn: `<p>Welcome to Multideal's contact page. We are here to help!</p>
<ul>
<li><strong>Email:</strong> support@multideal.co.il</li>
<li><strong>Hours:</strong> Sun–Thu, 9:00–18:00</li>
<li><strong>Response time:</strong> Up to 2 business days</li>
<li><strong>Urgent issues:</strong> <a href="https://wa.me/972500000000">WhatsApp</a></li>
</ul>`,
};

async function generateViaHaiku(apiKey: string, prompt: string): Promise<string> {
  // Dynamic import so the module loads even without the SDK when key absent
  const { default: Anthropic } = await import('@anthropic-ai/sdk');
  const client = new Anthropic({ apiKey });
  const msg = await client.messages.create({
    model: 'claude-haiku-4-5',
    max_tokens: 1024,
    messages: [{ role: 'user', content: prompt }],
  });
  const block = msg.content[0];
  if (block?.type !== 'text') throw new Error('Unexpected Haiku response');
  return block.text;
}

async function buildSeeds(): Promise<PageSeed[]> {
  const aboutHe = safeReadMd(resolve(CONTENT_DIR, 'about/about.he.md'));
  const aboutEn = safeReadMd(resolve(CONTENT_DIR, 'about/about.en.md'));
  const privacyHe = safeReadMd(resolve(CONTENT_DIR, 'legal/privacy.he.md'));
  const privacyEn = safeReadMd(resolve(CONTENT_DIR, 'legal/privacy.en.md'));
  const termsHe = safeReadMd(resolve(CONTENT_DIR, 'legal/tos-user.he.md'));
  const termsEn = safeReadMd(resolve(CONTENT_DIR, 'legal/tos-user.en.md'));
  const tosVHe = safeReadMd(resolve(CONTENT_DIR, 'legal/tos-vendor.he.md'));
  const tosVEn = safeReadMd(resolve(CONTENT_DIR, 'legal/tos-vendor.en.md'));
  const vouchHe = safeReadMd(resolve(CONTENT_DIR, 'legal/vouchers.he.md'));
  const vouchEn = safeReadMd(resolve(CONTENT_DIR, 'legal/vouchers.en.md'));
  const cookHe = safeReadMd(resolve(CONTENT_DIR, 'legal/cookies.he.md'));
  const cookEn = safeReadMd(resolve(CONTENT_DIR, 'legal/cookies.en.md'));
  const faqHe = combineFaq('he') || '<p>שאלות נפוצות</p>';
  const faqEn = combineFaq('en') || '<p>FAQ</p>';

  const apiKey = readOptionalAnthropicApiKey();
  let a11yHe: string;
  let a11yEn: string;
  let contactHe: string;
  let contactEn: string;

  if (apiKey) {
    scriptOutput('Generating accessibility content via Haiku...');
    a11yHe = await generateViaHaiku(
      apiKey,
      'Write a professional Hebrew accessibility statement (הצהרת נגישות) for מולטידיל (Multideal), a web marketplace for discounted deals from local Israeli businesses. Comply with IS 5568 and WCAG 2.1 AA. Include: compliance commitment, what we do, contact: accessibility@multideal.co.il, last audit: April 2026. Return ONLY HTML using <h2><p><ul><li> tags. No markdown, no intro text.',
    );
    a11yEn = await generateViaHaiku(
      apiKey,
      'Write a professional English accessibility statement for Multideal (מולטידיל), a web marketplace for discounted deals from local Israeli businesses. Comply with IS 5568 and WCAG 2.1 AA. Include: compliance commitment, what we do, contact: accessibility@multideal.co.il, last audit: April 2026. Return ONLY HTML using <h2><p><ul><li> tags. No markdown, no intro text.',
    );
    scriptOutput('Generating contact page content via Haiku...');
    contactHe = await generateViaHaiku(
      apiKey,
      'Write a Hebrew contact page for מולטידיל (Multideal), a marketplace for discounted deals from local Israeli businesses. Include: welcome paragraph, email: support@multideal.co.il, hours: Sun–Thu 9:00–18:00, response time: up to 2 business days, urgent issues: WhatsApp link. Return ONLY HTML using <p><ul><li><strong> tags. No markdown, no intro text.',
    );
    contactEn = await generateViaHaiku(
      apiKey,
      'Write an English contact page for Multideal, a marketplace for discounted deals from local Israeli businesses. Include: welcome paragraph, email: support@multideal.co.il, hours: Sun–Thu 9:00–18:00, response time: up to 2 business days, urgent: WhatsApp link. Return ONLY HTML using <p><ul><li><strong> tags. No markdown, no intro text.',
    );
  } else {
    scriptOutput(
      'ANTHROPIC_API_KEY not set — using hardcoded placeholder content for accessibility + contact.',
    );
    a11yHe = PLACEHOLDERS.a11yHe;
    a11yEn = PLACEHOLDERS.a11yEn;
    contactHe = PLACEHOLDERS.contactHe;
    contactEn = PLACEHOLDERS.contactEn;
  }

  return [
    {
      slug: 'about',
      layoutId: IDS['about']!.layout,
      heroId: IDS['about']!.hero,
      contentId: IDS['about']!.content,
      heroTitle: { he: 'אודות מולטידיל', en: 'About Multideal' },
      heroSubtitle: { he: 'פלטפורמת עסקאות מוזלות', en: 'Discounted-deals platform' },
      body: {
        he: aboutHe.html || '<p>אודות מולטידיל</p>',
        en: aboutEn.html || '<p>About Multideal</p>',
      },
    },
    {
      slug: 'faq',
      layoutId: IDS['faq']!.layout,
      heroId: IDS['faq']!.hero,
      contentId: IDS['faq']!.content,
      heroTitle: { he: 'שאלות נפוצות', en: 'FAQ' },
      heroSubtitle: { he: 'תשובות לשאלות הנפוצות', en: 'Answers to common questions' },
      body: { he: faqHe, en: faqEn },
    },
    {
      slug: 'legal/privacy',
      layoutId: IDS['legal/privacy']!.layout,
      heroId: IDS['legal/privacy']!.hero,
      contentId: IDS['legal/privacy']!.content,
      heroTitle: {
        he: privacyHe.title || 'מדיניות פרטיות',
        en: privacyEn.title || 'Privacy Policy',
      },
      heroSubtitle: { he: '', en: '' },
      body: {
        he: privacyHe.html || '<p>מדיניות פרטיות</p>',
        en: privacyEn.html || '<p>Privacy Policy</p>',
      },
    },
    {
      slug: 'legal/terms',
      layoutId: IDS['legal/terms']!.layout,
      heroId: IDS['legal/terms']!.hero,
      contentId: IDS['legal/terms']!.content,
      heroTitle: { he: termsHe.title || 'תנאי שימוש', en: termsEn.title || 'Terms of Service' },
      heroSubtitle: { he: '', en: '' },
      body: {
        he: termsHe.html || '<p>תנאי שימוש</p>',
        en: termsEn.html || '<p>Terms of Service</p>',
      },
    },
    {
      slug: 'legal/tos-vendor',
      layoutId: IDS['legal/tos-vendor']!.layout,
      heroId: IDS['legal/tos-vendor']!.hero,
      contentId: IDS['legal/tos-vendor']!.content,
      heroTitle: { he: tosVHe.title || 'תנאי שימוש לעסקים', en: tosVEn.title || 'Vendor Terms' },
      heroSubtitle: { he: '', en: '' },
      body: {
        he: tosVHe.html || '<p>תנאי שימוש לעסקים</p>',
        en: tosVEn.html || '<p>Vendor Terms</p>',
      },
    },
    {
      slug: 'legal/vouchers',
      layoutId: IDS['legal/vouchers']!.layout,
      heroId: IDS['legal/vouchers']!.hero,
      contentId: IDS['legal/vouchers']!.content,
      heroTitle: { he: vouchHe.title || 'תנאי שוברים', en: vouchEn.title || 'Voucher Terms' },
      heroSubtitle: { he: '', en: '' },
      body: {
        he: vouchHe.html || '<p>תנאי שוברים</p>',
        en: vouchEn.html || '<p>Voucher Terms</p>',
      },
    },
    {
      slug: 'legal/cookies',
      layoutId: IDS['legal/cookies']!.layout,
      heroId: IDS['legal/cookies']!.hero,
      contentId: IDS['legal/cookies']!.content,
      heroTitle: { he: cookHe.title || 'מדיניות עוגיות', en: cookEn.title || 'Cookie Policy' },
      heroSubtitle: { he: '', en: '' },
      body: {
        he: cookHe.html || '<p>מדיניות עוגיות</p>',
        en: cookEn.html || '<p>Cookie Policy</p>',
      },
    },
    {
      slug: 'accessibility',
      layoutId: IDS['accessibility']!.layout,
      heroId: IDS['accessibility']!.hero,
      contentId: IDS['accessibility']!.content,
      heroTitle: { he: 'הצהרת נגישות', en: 'Accessibility Statement' },
      heroSubtitle: { he: 'מחויבים לנגישות דיגיטלית', en: 'Committed to digital accessibility' },
      body: { he: a11yHe, en: a11yEn },
    },
    {
      slug: 'contact',
      layoutId: IDS['contact']!.layout,
      heroId: IDS['contact']!.hero,
      contentId: IDS['contact']!.content,
      heroTitle: { he: 'צור קשר', en: 'Contact Us' },
      heroSubtitle: { he: 'אנחנו כאן לעזור', en: 'We are here to help' },
      body: { he: contactHe, en: contactEn },
    },
  ];
}

async function main() {
  const DATABASE_URL = readSeedDatabaseUrl();

  const db = getDb({ DATABASE_URL });

  scriptOutput('Building static page seeds...');
  const seeds = await buildSeeds();
  const V = { guests: true, loggedIn: true };

  for (const s of seeds) {
    scriptOutput(`Seeding: ${s.slug}`);
    const body = {
      mobile: [
        {
          instanceId: s.heroId,
          type: 'page-hero',
          config: { title: s.heroTitle, subtitle: s.heroSubtitle },
          visibility: V,
        },
        {
          instanceId: s.contentId,
          type: 'rich-text-content',
          config: { body: s.body },
          visibility: V,
        },
      ],
      desktop: [
        {
          instanceId: s.heroId,
          type: 'page-hero',
          config: { title: s.heroTitle, subtitle: s.heroSubtitle },
          visibility: V,
        },
        {
          instanceId: s.contentId,
          type: 'rich-text-content',
          config: { body: s.body },
          visibility: V,
        },
      ],
    };
    await insertPageLayoutSeedRow(db, {
      id: s.layoutId,
      page: s.slug,
      body,
      note: 'Initial seed',
    });

    const existing = await db
      .select({ page: pageLayoutPointers.page })
      .from(pageLayoutPointers)
      .where(eq(pageLayoutPointers.page, s.slug))
      .limit(1);

    if (existing.length === 0) {
      await createLivePointer(db, s.slug, s.layoutId);
    } else {
      scriptOutput(`  pointer already exists, skipping`);
    }
  }

  scriptOutput(`\nSeeded ${seeds.length} static pages.`);
  process.exit(0);
}

main().catch((e) => {
  console.error('Seed failed:', e);
  process.exit(1);
});
