/**
 * Image Search Utility
 *
 * Searches the web for high-quality, royalty-free images using the Unsplash API.
 * Falls back gracefully when no API key is configured or rate limits are hit.
 *
 * Usage:
 *   const images = await searchImages('modern SaaS dashboard', 3);
 *   // Returns [{ url: 'https://images.unsplash.com/...', source: 'unsplash', description: '...' }]
 */

const UNSPLASH_ACCESS_KEY = process.env.UNSPLASH_ACCESS_KEY || '';
const UNSPLASH_API_URL = 'https://api.unsplash.com';

export interface SearchImageResult {
  url: string;
  thumbUrl: string;
  source: 'unsplash';
  description?: string;
  author?: string;
  authorUrl?: string;
}

/**
 * Search Unsplash for images matching a query.
 * Returns up to `count` results.
 * If no API key is set or the request fails, returns an empty array.
 */
export async function searchImages(
  query: string,
  count: number = 3
): Promise<SearchImageResult[]> {
  if (!UNSPLASH_ACCESS_KEY) {
    console.warn('[ImageSearch] No UNSPLASH_ACCESS_KEY configured — skipping web search tier.');
    return [];
  }

  if (!query || query.trim().length === 0) {
    return [];
  }

  try {
    const url = new URL(`${UNSPLASH_API_URL}/search/photos`);
    url.searchParams.set('query', query.trim());
    url.searchParams.set('per_page', String(Math.min(count, 10)));
    url.searchParams.set('orientation', 'landscape');

    const response = await fetch(url.toString(), {
      headers: {
        Authorization: `Client-ID ${UNSPLASH_ACCESS_KEY}`,
      },
      signal: AbortSignal.timeout(10000),
    });

    if (!response.ok) {
      const text = await response.text().catch(() => '');
      console.warn(`[ImageSearch] Unsplash API error ${response.status}: ${text}`);
      return [];
    }

    const data: any = await response.json();
    const results: SearchImageResult[] = [];

    if (Array.isArray(data.results)) {
      for (const item of data.results.slice(0, count)) {
        if (item?.urls?.regular && item?.urls?.small) {
          results.push({
            url: item.urls.regular,
            thumbUrl: item.urls.small,
            source: 'unsplash',
            description: item.description || item.alt_description || query,
            author: item.user?.name,
            authorUrl: item.user?.links?.html,
          });
        }
      }
    }

    console.log(`[ImageSearch] Found ${results.length} images for query: "${query}"`);
    return results;
  } catch (error: any) {
    console.warn('[ImageSearch] Failed to search images:', error.message);
    return [];
  }
}

/**
 * Build a contextual search query for a landing page section.
 * Combines business context with section content for targeted results.
 */
export function buildSectionImageQuery(
  section: { name?: string; type?: string; headline?: string; description?: string },
  businessContext: { companyName?: string; industry?: string; primaryOffering?: string }
): string {
  const parts: string[] = [];

  // Business context
  if (businessContext.primaryOffering) parts.push(businessContext.primaryOffering);
  else if (businessContext.companyName) parts.push(businessContext.companyName);

  if (businessContext.industry) parts.push(businessContext.industry);

  // Section context
  if (section.headline) parts.push(section.headline);
  else if (section.name) parts.push(section.name);

  if (section.description) {
    // Take first few words of description for search context
    const descWords = section.description.split(' ').slice(0, 8).join(' ');
    if (descWords.length > 10) parts.push(descWords);
  }

  // Section type hints
  const typeHints: Record<string, string> = {
    hero: 'hero banner background',
    features: 'product features showcase',
    benefits: 'business benefits illustration',
    testimonials: 'customer success professional',
    pricing: 'pricing plans business',
    'case-studies': 'business case study results',
    'social-proof': 'team office professional',
    'how-it-works': 'process workflow diagram',
    'cta-section': 'call to action business',
    statistics: 'data analytics charts',
    'founder-story': 'founder entrepreneur portrait',
    'comparison-table': 'comparison business',
    'video-block': 'video play button',
    'lead-form': 'contact form business',
    'pain-points': 'problem solution business',
    'solution-explanation': 'solution technology',
    'product-walkthrough': 'software product demo',
    'client-logos': 'company logos',
    'offer-breakdown': 'special offer promotion',
    bonuses: 'bonus gift reward',
    guarantee: 'guarantee shield badge',
    faqs: 'faq questions support',
    custom: 'business illustration',
  };

  const typeHint = typeHints[section.type || ''];
  if (typeHint) parts.push(typeHint);

  // Deduplicate and limit
  const uniqueParts = Array.from(new Set(parts.map(p => p.toLowerCase())));
  const query = uniqueParts.slice(0, 6).join(' ');

  return query || 'business professional';
}
