import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { hybridAI } from '@/lib/ai/hybridRouter';

// ─── Supported languages ──────────────────────────────────────────────────────
const SUPPORTED_LANGUAGES = ['en', 'es', 'pt', 'fr', 'de', 'zh', 'ja', 'ar', 'hi'] as const;
type LangCode = typeof SUPPORTED_LANGUAGES[number];

const LANGUAGE_NAMES: Record<LangCode, string> = {
  en: 'English', es: 'Español', pt: 'Português', fr: 'Français',
  de: 'Deutsch', zh: '中文', ja: '日本語', ar: 'العربية', hi: 'हिंदी',
};

// Priority order for 48hr backfill (Conflict 6 resolved)
const BACKFILL_PRIORITY: Record<LangCode, number> = {
  en: 10, es: 9, pt: 9, fr: 8, de: 8, ja: 7, zh: 7, ar: 6, hi: 6,
};

// ─── Translate content via Hybrid AI ─────────────────────────────────────────
async function translateContent(
  content: string,
  targetLang: LangCode,
  contentType: 'title' | 'body' | 'excerpt' | 'meta'
): Promise<string> {
  const langName = LANGUAGE_NAMES[targetLang];
  const maxTokens = contentType === 'body' ? 3000 : 300;

  const systemPrompt = `You are a professional translator specializing in broadcast technology and professional AV industry content. Translate from English to ${langName}.

Rules:
- Maintain the journalistic tone of the original
- Keep technical terms in their internationally recognized form (4K, AV-over-IP, HDMI, NAB, InfoComm, ISE, etc. do not need translation)
- Translate company names as written — do not translate proper nouns
- Adapt idiomatic expressions for the target culture rather than translating literally
- ${contentType === 'body' ? 'Maintain all HTML formatting tags in the output' : 'Return plain text only'}
- Keep SEO keywords as close to the original intent as possible in the target language
- Return ONLY the translated text, no explanations`;

  const userPrompt = contentType === 'meta'
    ? `Translate this SEO meta description to ${langName} (keep under 160 characters):\n\n${content}`
    : `Translate this ${contentType} to ${langName}:\n\n${content}`;

  const result = await hybridAI(
    [
      { role: 'system', content: systemPrompt },
      { role: 'user', content: userPrompt },
    ],
    { maxTokens, isBackground: true, priority: 5 }
  );

  return result.text.trim() || content;
}

// ─── GET ──────────────────────────────────────────────────────────────────────
export async function GET(request: NextRequest) {
  try {
    const supabase = await createClient();
    const { searchParams } = new URL(request.url);
    const action = searchParams.get('action');
    const postId = searchParams.get('post_id');
    const lang = searchParams.get('lang') as LangCode | null;

    // ── Get translation for a specific post + language ──
    if (action === 'get' && postId && lang) {
      const { data, error } = await supabase
        .from('translations')
        .select('*')
        .eq('post_id', postId)
        .eq('language_code', lang)
        .single();

      if (error && error.code !== 'PGRST116') {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }

      return NextResponse.json({ translation: data || null });
    }

    // ── Get all translations for a post ──
    if (action === 'all' && postId) {
      const { data, error } = await supabase
        .from('translations')
        .select('language_code, title_translated, meta_description_translated, is_stale, generated_at')
        .eq('post_id', postId);

      if (error) return NextResponse.json({ error: error.message }, { status: 500 });
      return NextResponse.json({ translations: data || [] });
    }

    // ── Get translation queue stats ──
    if (action === 'queue_stats') {
      const { data } = await supabase
        .from('translation_queue')
        .select('language_code, status')
        .eq('status', 'pending');

      const stats: Record<string, number> = {};
      (data || []).forEach((item: any) => {
        stats[item.language_code] = (stats[item.language_code] || 0) + 1;
      });

      return NextResponse.json({ queueStats: stats, supportedLanguages: SUPPORTED_LANGUAGES });
    }

    // ── Get UI translations for a language ──
    if (action === 'ui' && lang) {
      const { data } = await supabase
        .from('ui_translations')
        .select('key, value')
        .eq('language_code', lang);

      const translations: Record<string, string> = {};
      (data || []).forEach((item: any) => { translations[item.key] = item.value; });
      return NextResponse.json({ translations });
    }

    return NextResponse.json({ error: 'Unknown action' }, { status: 400 });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}

// ─── POST ─────────────────────────────────────────────────────────────────────
export async function POST(request: NextRequest) {
  try {
    const supabase = await createClient();
    const body = await request.json();
    const { action } = body;

    // ── Translate a single post into a specific language (lazy on-demand) ──
    if (action === 'translate') {
      const { post_id, post_type = 'native', language_code } = body;

      if (!SUPPORTED_LANGUAGES.includes(language_code as LangCode)) {
        return NextResponse.json({ error: 'Unsupported language' }, { status: 400 });
      }

      // Check if translation already exists and is not stale
      const { data: existing } = await supabase
        .from('translations')
        .select('*')
        .eq('post_id', post_id)
        .eq('language_code', language_code)
        .single();

      if (existing && !existing.is_stale) {
        return NextResponse.json({ translation: existing, cached: true });
      }

      // Fetch source article
      const table = post_type === 'imported' ? 'wp_imported_posts' : 'native_articles';
      const titleField = post_type === 'imported' ? 'title' : 'title';
      const contentField = post_type === 'imported' ? 'content' : 'content';
      const excerptField = post_type === 'imported' ? 'excerpt' : 'excerpt';

      const { data: article, error: articleError } = await supabase
        .from(table)
        .select(`${titleField}, ${contentField}, ${excerptField}`)
        .eq('id', post_id)
        .single();

      if (articleError || !article) {
        return NextResponse.json({ error: 'Article not found' }, { status: 404 });
      }

      const lang = language_code as LangCode;

      // Translate all fields
      const [titleTranslated, excerptTranslated, metaTranslated] = await Promise.all([
        translateContent(article.title || '', lang, 'title'),
        translateContent(article.excerpt || article.title || '', lang, 'excerpt'),
        translateContent(article.excerpt || article.title || '', lang, 'meta'),
      ]);

      // Translate body (longer, do separately)
      const contentTranslated = await translateContent(article.content || '', lang, 'body');

      const wordCount = contentTranslated.split(/\s+/).length;

      // Upsert translation
      const { data: saved, error: saveError } = await supabase
        .from('translations')
        .upsert({
          post_id,
          post_type,
          language_code,
          title_translated: titleTranslated,
          content_translated: contentTranslated,
          excerpt_translated: excerptTranslated,
          meta_description_translated: metaTranslated,
          generated_at: new Date().toISOString(),
          is_stale: false,
          word_count: wordCount,
        }, { onConflict: 'post_id,language_code' })
        .select()
        .single();

      if (saveError) return NextResponse.json({ error: saveError.message }, { status: 500 });

      // Mark queue item as completed
      await supabase
        .from('translation_queue')
        .update({ status: 'completed', processed_at: new Date().toISOString() })
        .eq('post_id', post_id)
        .eq('language_code', language_code);

      return NextResponse.json({ translation: saved, cached: false });
    }

    // ── Queue translations for a newly published post ──
    if (action === 'queue_translations') {
      const { post_id, post_type = 'native', priority_boost = 0 } = body;

      const languages: LangCode[] = ['es', 'pt', 'fr', 'de', 'zh', 'ja', 'ar', 'hi'];
      const jobs = languages.map(lang => ({
        post_id,
        post_type,
        language_code: lang,
        priority: BACKFILL_PRIORITY[lang] + priority_boost,
        status: 'pending',
      }));

      const { error } = await supabase
        .from('translation_queue')
        .upsert(jobs, { onConflict: 'post_id,language_code,status', ignoreDuplicates: true });

      if (error) return NextResponse.json({ error: error.message }, { status: 500 });
      return NextResponse.json({ success: true, queued: languages.length });
    }

    // ── Process next item in translation queue ──
    if (action === 'process_queue') {
      const { limit = 5 } = body;

      const { data: pending } = await supabase
        .from('translation_queue')
        .select('*')
        .eq('status', 'pending')
        .order('priority', { ascending: false })
        .order('queued_at', { ascending: true })
        .limit(limit);

      if (!pending || pending.length === 0) {
        return NextResponse.json({ processed: 0, message: 'Queue empty' });
      }

      let processed = 0;
      for (const job of pending) {
        try {
          // Mark as processing
          await supabase
            .from('translation_queue')
            .update({ status: 'processing' })
            .eq('id', job.id);

          // Trigger translation
          const translateRes = await fetch(`${process.env.NEXT_PUBLIC_SITE_URL}/api/translations`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              action: 'translate',
              post_id: job.post_id,
              post_type: job.post_type,
              language_code: job.language_code,
            }),
          });

          if (translateRes.ok) {
            processed++;
          } else {
            await supabase
              .from('translation_queue')
              .update({ status: 'failed', error_message: 'Translation failed' })
              .eq('id', job.id);
          }
        } catch (err: any) {
          await supabase
            .from('translation_queue')
            .update({ status: 'failed', error_message: err.message })
            .eq('id', job.id);
        }
      }

      return NextResponse.json({ processed, total: pending.length });
    }

    // ── Mark translations stale when source is updated ──
    if (action === 'mark_stale') {
      const { post_id } = body;
      await supabase
        .from('translations')
        .update({ is_stale: true })
        .eq('post_id', post_id);

      // Re-queue all languages
      const languages: LangCode[] = ['es', 'pt', 'fr', 'de', 'zh', 'ja', 'ar', 'hi'];
      const jobs = languages.map(lang => ({
        post_id,
        post_type: 'native',
        language_code: lang,
        priority: BACKFILL_PRIORITY[lang],
        status: 'pending',
      }));

      await supabase
        .from('translation_queue')
        .upsert(jobs, { onConflict: 'post_id,language_code,status', ignoreDuplicates: true });

      return NextResponse.json({ success: true });
    }

    return NextResponse.json({ error: 'Unknown action' }, { status: 400 });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
