import fs from 'fs';
import path from 'path';

/**
 * Finds the datasheet PDF path for a given product slug and locale.
 * Checks public/datasheets for matching files.
 */
export function getDatasheetPath(slug: string, locale: string): string | null {
  const datasheetsDir = path.join(process.cwd(), 'public', 'datasheets');
  
  if (!fs.existsSync(datasheetsDir)) {
    return null;
  }

  // Normalize slug: remove common suffixes that might not be in the PDF filename
  const normalizedSlug = slug.replace(/-hv$|-mv$/, '');

  // Subdirectories to search in
  const subdirs = ['', 'low-voltage', 'medium-voltage', 'high-voltage', 'solar'];

  // List of patterns to try for the current locale
  const patterns = [
    `${slug}-${locale}.pdf`,
    `${slug}-2-${locale}.pdf`,
    `${slug}-3-${locale}.pdf`,
    `${normalizedSlug}-${locale}.pdf`,
    `${normalizedSlug}-2-${locale}.pdf`,
    `${normalizedSlug}-3-${locale}.pdf`,
  ];

  for (const subdir of subdirs) {
    for (const pattern of patterns) {
      const relativePath = path.join(subdir, pattern);
      const filePath = path.join(datasheetsDir, relativePath);
      if (fs.existsSync(filePath)) {
        return `/datasheets/${relativePath}`;
      }
    }
  }

  // Fallback to English if locale is not 'en'
  if (locale !== 'en') {
    const enPatterns = [
      `${slug}-en.pdf`,
      `${slug}-2-en.pdf`,
      `${slug}-3-en.pdf`,
      `${normalizedSlug}-en.pdf`,
      `${normalizedSlug}-2-en.pdf`,
      `${normalizedSlug}-3-en.pdf`,
    ];
    for (const subdir of subdirs) {
      for (const pattern of enPatterns) {
        const relativePath = path.join(subdir, pattern);
        const filePath = path.join(datasheetsDir, relativePath);
        if (fs.existsSync(filePath)) {
          return `/datasheets/${relativePath}`;
        }
      }
    }
  }

  return null;
}
