import { readFileSync, existsSync, mkdirSync } from 'fs';
import { join } from 'path';
import { cache } from 'react';
import type { Partner, SiteInfo } from '@/types/data';

const DATA_DIR = join(process.cwd(), 'data');

// Cache file reads per request to avoid multiple reads
const readFileCached = cache((filePath: string) => {
  try {
    return readFileSync(filePath, 'utf-8');
  } catch (error) {
    console.error(`Error reading file ${filePath}:`, error);
    return null;
  }
});

/**
 * Ensures the data directory exists
 */
function ensureDataDir() {
  if (!existsSync(DATA_DIR)) {
    mkdirSync(DATA_DIR, { recursive: true });
  }
}

/**
 * Reads partners.json at runtime
 * Filters to only return partners with display: true
 * Uses React cache to avoid multiple file reads per request
 */
export const getPartners = cache((): Partner[] => {
  ensureDataDir();
  const filePath = join(DATA_DIR, 'partners.json');
  
  const fileContent = readFileCached(filePath);
  if (!fileContent) return [];
  
  try {
    const allPartners = JSON.parse(fileContent) as Partner[];
    // Filter to only show partners with display: true (defaults to true if not specified)
    return allPartners.filter((partner) => partner.display !== false);
  } catch (error) {
    console.error('Error parsing partners.json:', error);
    return [];
  }
});

const DEFAULT_SITE_INFO: SiteInfo = {
  siteName: 'BetRanker',
  siteLogo: '/logo.png',
  email: 'support@betranked.com',
  address: 'London, UK',
  phone: '+44 20 1234 5678',
  accountCode: 'BET-UK02KS',
  tagline: 'Top-Rated UK Betting Platforms',
  favicon: '/favicon.ico',
  browserTitle: 'Top-Rated UK Betting Platforms',
  defaultLanguage: 'pt', // Default site language
  defaultTheme: '2', // Default site theme
} as const;

/**
 * Reads siteinfo.json at runtime
 * Uses React cache to avoid multiple file reads per request
 */
export const getSiteInfo = cache((): SiteInfo => {
  ensureDataDir();
  const filePath = join(DATA_DIR, 'siteinfo.json');
  
  const fileContent = readFileCached(filePath);
  if (!fileContent) return DEFAULT_SITE_INFO;
  
  try {
    return JSON.parse(fileContent) as SiteInfo;
  } catch (error) {
    console.error('Error parsing siteinfo.json:', error);
    return DEFAULT_SITE_INFO;
  }
});

/**
 * Gets the data directory path
 */
export function getDataDir(): string {
  ensureDataDir();
  return DATA_DIR;
}

