import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { join } from 'path';
import { getDataDir } from './data';

const VISITORS_FILE = 'visitors.json';

export type VisitorEntry = {
  url: string;
  timestamp: number;
  userAgent?: string;
  referer?: string;
};

export type VisitorsData = {
  entries: VisitorEntry[];
  totalVisitors?: number; // Total count that persists even when entries are trimmed
};

/**
 * Gets the visitors data file path
 */
function getVisitorsFilePath(): string {
  const dataDir = getDataDir();
  return join(dataDir, VISITORS_FILE);
}

/**
 * Reads visitors.json at runtime
 */
export function getVisitors(): VisitorsData {
  const filePath = getVisitorsFilePath();
  
  try {
    if (!existsSync(filePath)) {
      return { entries: [], totalVisitors: 0 };
    }
    const fileContent = readFileSync(filePath, 'utf-8');
    const data = JSON.parse(fileContent) as VisitorsData;
    // Ensure totalVisitors exists (for backward compatibility)
    if (data.totalVisitors === undefined) {
      data.totalVisitors = data.entries.length;
    }
    return data;
  } catch (error) {
    console.error('Error reading visitors.json:', error);
    return { entries: [], totalVisitors: 0 };
  }
}

/**
 * Adds a visitor entry
 */
export function addVisitor(entry: VisitorEntry): void {
  const filePath = getVisitorsFilePath();
  const visitors = getVisitors();
  
  // Initialize totalVisitors if it doesn't exist (backward compatibility)
  if (visitors.totalVisitors === undefined) {
    visitors.totalVisitors = visitors.entries.length;
  }
  
  // Increment total visitor count
  visitors.totalVisitors = (visitors.totalVisitors || 0) + 1;
  
  // Add new entry at the beginning
  visitors.entries.unshift(entry);
  
  // Keep only last 1000 entries to prevent file from growing too large
  // Note: totalVisitors counter persists even when entries are trimmed
  if (visitors.entries.length > 1000) {
    visitors.entries = visitors.entries.slice(0, 1000);
  }
  
  try {
    writeFileSync(filePath, JSON.stringify(visitors, null, 2));
  } catch (error) {
    console.error('Error writing visitors.json:', error);
  }
}

/**
 * Resets all visitors
 */
export function resetVisitors(): void {
  const filePath = getVisitorsFilePath();
  
  try {
    writeFileSync(filePath, JSON.stringify({ entries: [], totalVisitors: 0 }, null, 2));
  } catch (error) {
    console.error('Error resetting visitors.json:', error);
    throw error;
  }
}

