import { NextResponse } from 'next/server';
import { parseDate } from '@/lib/utils';

const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://spanglish.com.py';
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';

interface LlmsFaq {
  question: string;
  answer: string;
}

interface LlmsEvent {
  id: string;
  slug: string;
  title: string;
  titleEs?: string;
  shortDescription?: string;
  shortDescriptionEs?: string;
  description: string;
  descriptionEs?: string;
  startDatetime: string;
  endDatetime?: string;
  location: string;
  price: number;
  currency: string;
  availableSeats?: number;
  status: string;
}

async function getNextUpcomingEvent(): Promise<LlmsEvent | null> {
  try {
    const response = await fetch(`${apiUrl}/api/events/next/upcoming`, {
      cache: 'no-store',
    });
    if (!response.ok) return null;
    const data = await response.json();
    return data.event || null;
  } catch {
    return null;
  }
}

async function getUpcomingEvents(): Promise<LlmsEvent[]> {
  try {
    const response = await fetch(`${apiUrl}/api/events?status=published&upcoming=true`, {
      cache: 'no-store',
    });
    if (!response.ok) return [];
    const data = await response.json();
    return data.events || [];
  } catch {
    return [];
  }
}

// Event times are always shown in Paraguay time (America/Asuncion) so llms.txt
// matches what users see on the website, regardless of server timezone.
const EVENT_TIMEZONE = 'America/Asuncion';

function formatEventDate(dateStr: string): string {
  return parseDate(dateStr).toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    timeZone: EVENT_TIMEZONE,
  });
}

function formatEventTime(dateStr: string): string {
  return parseDate(dateStr).toLocaleTimeString('en-US', {
    hour: '2-digit',
    minute: '2-digit',
    hour12: true,
    timeZone: EVENT_TIMEZONE,
  });
}

function formatPrice(price: number, currency: string): string {
  if (price === 0) return 'Free';
  return `${price.toLocaleString()} ${currency}`;
}

function formatISODate(dateStr: string): string {
  return parseDate(dateStr).toLocaleDateString('en-CA', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    timeZone: EVENT_TIMEZONE,
  });
}

function formatISOTime(dateStr: string): string {
  return parseDate(dateStr).toLocaleTimeString('en-GB', {
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
    timeZone: EVENT_TIMEZONE,
  });
}

function getTodayISO(): string {
  return new Date().toLocaleDateString('en-CA', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    timeZone: EVENT_TIMEZONE,
  });
}

function getEventStatus(event: LlmsEvent): string {
  if (event.availableSeats !== undefined && event.availableSeats === 0) return 'Sold Out';
  if (event.status === 'published') return 'Available';
  return event.status;
}

async function getHomepageFaqs(): Promise<LlmsFaq[]> {
  try {
    const response = await fetch(`${apiUrl}/api/faq?homepage=true`, {
      cache: 'no-store',
    });
    if (!response.ok) return [];
    const data = await response.json();
    return (data.faqs || []).map((f: any) => ({
      question: f.question,
      answer: f.answer,
    }));
  } catch {
    return [];
  }
}

export const dynamic = 'force-dynamic';

export async function GET() {
  const [nextEvent, upcomingEvents, faqs] = await Promise.all([
    getNextUpcomingEvent(),
    getUpcomingEvents(),
    getHomepageFaqs(),
  ]);

  const lines: string[] = [];

  // Header
  lines.push('# Spanglish Community');
  lines.push('');
  lines.push('## Metadata');
  lines.push('');
  lines.push('- Type: Event Community');
  lines.push('- Primary Language: English, Spanish');
  lines.push('- Location: Asunción, Paraguay');
  lines.push(`- Time Zone: ${EVENT_TIMEZONE}`);
  lines.push(`- Last Updated: ${getTodayISO()}`);
  lines.push(`- Canonical URL: ${siteUrl}`);
  lines.push('');
  lines.push('> English-Spanish language exchange community organizing social events and meetups in Asunción, Paraguay.');
  lines.push('');
  lines.push(`- Website: ${siteUrl}`);
  lines.push(`- Events page: ${siteUrl}/events`);

  // Social links
  const instagram = process.env.NEXT_PUBLIC_INSTAGRAM;
  const whatsapp = process.env.NEXT_PUBLIC_WHATSAPP;
  const telegram = process.env.NEXT_PUBLIC_TELEGRAM;
  const email = process.env.NEXT_PUBLIC_EMAIL;

  if (instagram) lines.push(`- Instagram: ${instagram}`);
  if (telegram) lines.push(`- Telegram: ${telegram}`);
  if (email) lines.push(`- Email: ${email}`);
  if (whatsapp) lines.push(`- WhatsApp: ${whatsapp}`);

  lines.push('');

  // Next Event (most important section for AI)
  lines.push('## Next Event');
  lines.push('');

  if (nextEvent) {
    const status = getEventStatus(nextEvent);
    lines.push(`- Event Name: ${nextEvent.title}`);
    lines.push(`- Event ID: ${nextEvent.id}`);
    lines.push(`- Status: ${status}`);
    lines.push(`- Date: ${formatISODate(nextEvent.startDatetime)}`);
    lines.push(`- Start Time: ${formatISOTime(nextEvent.startDatetime)}`);
    if (nextEvent.endDatetime) {
      lines.push(`- End Time: ${formatISOTime(nextEvent.endDatetime)}`);
    }
    lines.push(`- Time Zone: ${EVENT_TIMEZONE}`);
    lines.push(`- Venue: ${nextEvent.location}`);
    lines.push('- City: Asunción');
    lines.push('- Country: Paraguay');
    lines.push(`- Price: ${nextEvent.price === 0 ? 'Free' : nextEvent.price}`);
    lines.push(`- Currency: ${nextEvent.currency}`);
    if (nextEvent.availableSeats !== undefined) {
      lines.push(`- Capacity Remaining: ${nextEvent.availableSeats}`);
    }
    lines.push(`- Tickets URL: ${siteUrl}/events/${nextEvent.slug}`);
    if (nextEvent.shortDescription) {
      lines.push(`- Description: ${nextEvent.shortDescription}`);
    }
  } else {
    lines.push('No upcoming events currently scheduled. Check back soon or follow us on social media for announcements.');
  }

  lines.push('');

  // All upcoming events
  if (upcomingEvents.length > 1) {
    lines.push('## All Upcoming Events');
    lines.push('');
    for (const event of upcomingEvents) {
      const status = getEventStatus(event);
      lines.push(`### ${event.title}`);
      lines.push(`- Event ID: ${event.id}`);
      lines.push(`- Status: ${status}`);
      lines.push(`- Date: ${formatISODate(event.startDatetime)}`);
      lines.push(`- Start Time: ${formatISOTime(event.startDatetime)}`);
      if (event.endDatetime) {
        lines.push(`- End Time: ${formatISOTime(event.endDatetime)}`);
      }
      lines.push(`- Time Zone: ${EVENT_TIMEZONE}`);
      lines.push(`- Venue: ${event.location}`);
      lines.push('- City: Asunción');
      lines.push('- Country: Paraguay');
      lines.push(`- Price: ${event.price === 0 ? 'Free' : event.price}`);
      lines.push(`- Currency: ${event.currency}`);
      if (event.availableSeats !== undefined) {
        lines.push(`- Capacity Remaining: ${event.availableSeats}`);
      }
      lines.push(`- Tickets URL: ${siteUrl}/events/${event.slug}`);
      lines.push('');
    }
  }

  // About section
  lines.push('## About Spanglish');
  lines.push('');
  lines.push('Spanglish is a language exchange community based in Asunción, Paraguay. We organize regular social events where people can practice English and Spanish in a relaxed, friendly environment. Our events bring together locals and internationals for conversation, cultural exchange, and fun.');
  lines.push('');
  lines.push('## Frequently Asked Questions');
  lines.push('');
  if (faqs.length > 0) {
    for (const faq of faqs) {
      lines.push(`- **${faq.question}** ${faq.answer}`);
    }
  } else {
    lines.push('- **What is Spanglish?** A language exchange community that hosts social events to practice English and Spanish.');
    lines.push('- **Where are events held?** In Asunción, Paraguay. Specific venues are listed on each event page.');
    lines.push('- **How do I attend an event?** Visit the events page to see upcoming events and book tickets.');
  }
  lines.push(`- More FAQ: ${siteUrl}/faq`);
  lines.push('');

  // Update Policy
  lines.push('## Update Policy');
  lines.push('');
  lines.push('Event information is updated whenever new events are published or ticket availability changes.');
  lines.push('');

  // AI Summary
  lines.push('## AI Summary');
  lines.push('');
  lines.push('Spanglish Community organizes English-Spanish language exchange events in Asunción, Paraguay. Events require registration via the website.');
  lines.push('');

  const content = lines.join('\n');

  return new NextResponse(content, {
    headers: {
      'Content-Type': 'text/plain; charset=utf-8',
      'Cache-Control': 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400',
    },
  });
}
