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

// Define paths
const APALAH_DIR = path.join(process.cwd(), 'apalah');
const KEYW_DIR = path.join(process.cwd(), 'keyw');

export interface ArticleData {
  title: string;
  description: string;
  description_alt: string;
  questions: Array<{ question: string; answer: string }>;
  related_keywords: string[];
}

export interface ArticlePreview {
  slug: string;
  originalFileName: string;
  title: string;
}

// Get top-level categories
export async function getCategories(): Promise<string[]> {
  if (!fs.existsSync(APALAH_DIR)) return [];
  return fs.readdirSync(APALAH_DIR).filter(file => {
    return fs.statSync(path.join(APALAH_DIR, file)).isDirectory();
  });
}

// Get sub-categories
export async function getSubCategories(cat1: string): Promise<string[]> {
  const dirPath = path.join(APALAH_DIR, cat1);
  if (!fs.existsSync(dirPath)) return [];
  return fs.readdirSync(dirPath).filter(file => {
    return fs.statSync(path.join(dirPath, file)).isDirectory();
  });
}

// Array of 10 dynamic prefixes
export const URL_PREFIXES = [
  "download", "read", "watch", "best", "top", 
  "free", "online", "get", "new", "guide"
];

// Helper to convert filename to a smart dynamic slug
export function filenameToSlug(filename: string): string {
  // Remove trailing "json"
  let cleanName = filename;
  if (cleanName.endsWith('json')) {
    cleanName = cleanName.slice(0, -4).trim();
  }
  const words = cleanName.split(/\s+/).map(w => w.toLowerCase());
  
  // Randomize prefix on every load to generate infinite internal link permutations
  const prefix = URL_PREFIXES[Math.floor(Math.random() * URL_PREFIXES.length)];
  
  // Combine all words
  const allWords = [prefix, ...words];
  
  // Choose random style (0: kebab, 1: snake, 2: mixed, 3: camelCase)
  const style = Math.floor(Math.random() * 4);
  
  if (style === 3) {
    // Camel Case
    let result = allWords[0];
    for (let i = 1; i < allWords.length; i++) {
      result += allWords[i].charAt(0).toUpperCase() + allWords[i].slice(1);
    }
    return result;
  }
  
  // Kebab, Snake, or Mixed
  let result = allWords[0];
  for (let i = 1; i < allWords.length; i++) {
    let sep = '-';
    if (style === 1) sep = '_';
    else if (style === 2) sep = Math.random() > 0.5 ? '-' : '_';
    
    result += sep + allWords[i];
  }
  
  return result;
}

// Get all articles in a sub-category by reading the keyw file
export async function getArticles(cat1: string, cat2: string): Promise<ArticlePreview[]> {
  const keywFilePath = path.join(KEYW_DIR, cat1, cat2);
  if (!fs.existsSync(keywFilePath)) return [];

  const fileContents = fs.readFileSync(keywFilePath, 'utf8');
  const lines = fileContents.split('\n').filter(line => line.trim() !== '');

  return lines.map(line => {
    const originalFileName = line.trim();
    return {
      slug: filenameToSlug(originalFileName),
      originalFileName,
      // Create a basic title from the slug without the ID
      title: originalFileName.replace(/^[a-zA-Z0-9]+\s/, '').replace(/json$/, '').trim(),
    };
  });
}

// Helper to extract the unique ID from a filename
export function getUniqueId(str: string): string {
  // The unique ID is always the first block of alphanumeric characters in the original filename
  const match = str.match(/^([a-zA-Z0-9]{5,8})\s/);
  return match ? match[1].toLowerCase() : '';
}

// Get article data
export async function getArticleBySlug(cat1: string, cat2: string, slug: string): Promise<ArticleData | null> {
  const articles = await getArticles(cat1, cat2);
  const slugLower = slug.toLowerCase();
  
  // Deteksi artikel secara dinamis meskipun slug telah ditambahkan prefix/suffix apapun
  const article = articles.find(a => {
    const id = getUniqueId(a.originalFileName);
    // Jika slug URL mengandung ID unik 6-karakter dari filename, maka cocok!
    return id && slugLower.includes(id);
  });
  
  if (!article) return null;

  const jsonFilePath = path.join(APALAH_DIR, cat1, cat2, article.originalFileName);
  if (!fs.existsSync(jsonFilePath)) return null;

  try {
    const fileContents = fs.readFileSync(jsonFilePath, 'utf8');
    return JSON.parse(fileContents) as ArticleData;
  } catch (err) {
    console.error(`Error reading or parsing JSON: ${jsonFilePath}`, err);
    return null;
  }
}

// Get a sample of articles cross-category for RSS/Global feeds (Randomized)
export async function getSampleArticles(limit: number = 500): Promise<Array<ArticlePreview & { cat1: string, cat2: string }>> {
  const categories = await getCategories();
  // Shuffle categories
  const shuffledCats = [...categories].sort(() => Math.random() - 0.5);
  
  const results: Array<ArticlePreview & { cat1: string, cat2: string }> = [];

  for (const cat1 of shuffledCats) {
    if (results.length >= limit) break;
    const subCats = await getSubCategories(cat1);
    // Shuffle sub-categories
    const shuffledSubCats = [...subCats].sort(() => Math.random() - 0.5);
    
    for (const cat2 of shuffledSubCats) {
      if (results.length >= limit) break;
      const articles = await getArticles(cat1, cat2);
      if (articles.length === 0) continue;

      // Ambil 5-10 artikel secara acak dari setiap sub-kategori
      const randomArticles = [...articles]
        .sort(() => Math.random() - 0.5)
        .slice(0, 10)
        .map(a => ({ ...a, cat1, cat2 }));
        
      results.push(...randomArticles);
    }
  }

  // Shuffle hasil akhir agar urutan kategori tercampur rata
  return results.sort(() => Math.random() - 0.5).slice(0, limit);
}
