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

const CLICKS_FILE = 'clicks.json';

export type ClickData = {
  [partnerName: string]: number;
};

/**
 * Gets the clicks data file path
 */
function getClicksFilePath(): string {
  const dataDir = getDataDir();
  return join(dataDir, CLICKS_FILE);
}

/**
 * Reads clicks.json at runtime
 */
export function getClicks(): ClickData {
  const filePath = getClicksFilePath();
  
  try {
    if (!existsSync(filePath)) {
      return {};
    }
    const fileContent = readFileSync(filePath, 'utf-8');
    return JSON.parse(fileContent) as ClickData;
  } catch (error) {
    console.error('Error reading clicks.json:', error);
    return {};
  }
}

/**
 * Increments click count for a partner
 */
export function incrementClick(partnerName: string): void {
  const filePath = getClicksFilePath();
  const clicks = getClicks();
  
  clicks[partnerName] = (clicks[partnerName] || 0) + 1;
  
  try {
    writeFileSync(filePath, JSON.stringify(clicks, null, 2));
  } catch (error) {
    console.error('Error writing clicks.json:', error);
  }
}

/**
 * Resets all clicks
 */
export function resetClicks(): void {
  const filePath = getClicksFilePath();
  
  try {
    writeFileSync(filePath, JSON.stringify({}, null, 2));
  } catch (error) {
    console.error('Error resetting clicks.json:', error);
    throw error;
  }
}

