const path = require('path');
const fs = require('fs');
require('dotenv').config();

function bool(name, fallback = false) {
  const value = process.env[name];
  if (value == null || value === '') return fallback;
  return ['1', 'true', 'yes', 'on'].includes(String(value).toLowerCase());
}

function int(name, fallback) {
  const value = Number(process.env[name]);
  return Number.isFinite(value) ? value : fallback;
}

function str(name, fallback = '') {
  return process.env[name] || fallback;
}

function intList(name, fallback) {
  const value = str(name, '');
  if (!value) return fallback;
  const parsed = value
    .split(',')
    .map((entry) => Number(entry.trim()))
    .filter((entry) => Number.isInteger(entry));
  return parsed.length > 0 ? parsed : fallback;
}

function slugify(value) {
  return String(value || '')
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

function uniqueBots(bots) {
  const seen = new Set();
  return bots.filter((bot) => {
    const key = bot.key || slugify(bot.name) || slugify(bot.url);
    if (!key || seen.has(key)) return false;
    seen.add(key);
    bot.key = key;
    return true;
  });
}

function parseBots(name, fallback) {
  const value = str(name, '');
  if (!value) return fallback;

  const bots = value
    .split(/\r?\n|\|/)
    .map((entry) => entry.trim())
    .filter(Boolean)
    .map((entry, index) => {
      const [rawName, rawUrl] = entry.includes('=') ? entry.split('=') : [`bot-${index + 1}`, entry];
      const nameValue = String(rawName || '').trim();
      const urlValue = String(rawUrl || '').trim();
      return {
        key: slugify(nameValue) || `bot-${index + 1}`,
        name: nameValue || `Bot ${index + 1}`,
        url: urlValue
      };
    })
    .filter((bot) => bot.url);

  return bots.length > 0 ? uniqueBots(bots) : fallback;
}

const rootDir = path.resolve(__dirname, '..');
const sessionFile = path.resolve(rootDir, str('SESSION_FILE', './data/alpinbet-session.json'));
const stateFile = path.resolve(rootDir, str('STATE_FILE', './data/last-state.json'));
const heartbeatFile = path.resolve(rootDir, str('HEARTBEAT_FILE', './data/heartbeat.json'));
const htmlSnapshotDir = path.resolve(rootDir, str('HTML_SNAPSHOT_DIR', './data/html'));
const defaultBots = uniqueBots([
  {
    key: 'raketafon',
    name: 'Raketafon',
    url: 'https://alpinbet.com/dispatch/antigol/raketafon'
  },
  {
    key: 'pobeda-1-comand',
    name: 'Pobeda 1 Comand',
    url: 'https://alpinbet.com/dispatch/antigol/pobeda-1-comand'
  },
  {
    key: 'raketabas',
    name: 'Raketabas',
    url: 'https://alpinbet.com/dispatch/antigol/raketabas'
  },
  
  {
    key: 'sol-1www',
    name: 'Sol 1www',
    url: 'https://alpinbet.com/dispatch/antigol/sol-1www'
  },
  {
    key: 'fon-stb',
    name: 'Fon Stb',
    url: 'https://alpinbet.com/dispatch/antigol/fon-stb'
  },
  {
    key: 'fonat',
    name: 'Fonat',
    url: 'https://alpinbet.com/dispatch/antigol/fonat'
  }
]);

for (const dir of [path.dirname(sessionFile), path.dirname(stateFile), path.dirname(heartbeatFile), htmlSnapshotDir]) {
  fs.mkdirSync(dir, { recursive: true });
}

module.exports = {
  providerId: str('PROVIDER_ID', 'alpinbet'),
  baseUrl: str('ALPINBET_BASE_URL', 'https://alpinbet.com/'),
  targetUrl: str('ALPINBET_TARGET_URL', defaultBots[0]?.url || 'https://alpinbet.com/bot/my-live'),
  bots: parseBots('ALPINBET_BOTS', defaultBots),
  headless: bool('HEADLESS', true),
  authHeadless: bool('AUTH_HEADLESS', false),
  httpUserAgent: str(
    'HTTP_USER_AGENT',
    'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36'
  ),
  authEnabled: bool('AUTH_ENABLED', false),
  authLoginUrl: str('AUTH_LOGIN_URL', 'https://alpinbet.com/site/login'),
  authUsername: str('AUTH_USERNAME', ''),
  authPassword: str('AUTH_PASSWORD', ''),
  authUsernameSelector: str('AUTH_USERNAME_SELECTOR', 'input[name=\"LoginForm[login]\"], input[name=\"LoginForm[email]\"], input[name=\"email\"], input[type=\"email\"], input[name=\"login\"], input[name=\"username\"]'),
  authPasswordSelector: str('AUTH_PASSWORD_SELECTOR', 'input[name=\"LoginForm[password]\"], input[name=\"password\"], input[type=\"password\"]'),
  authSubmitSelector: str('AUTH_SUBMIT_SELECTOR', 'button[type=\"submit\"], input[type=\"submit\"], .login button, .auth button'),
  authSuccessSelector: str('AUTH_SUCCESS_SELECTOR', '#currentUser, .user-card, .currentUser'),
  authLoginDetectUrlPart: str('AUTH_LOGIN_DETECT_URL_PART', '/site/login'),
  pollIntervalMs: int('POLL_INTERVAL_MS', 20000),
  requestTimeoutMs: int('REQUEST_TIMEOUT_MS', 45000),
  sessionFile,
  stateFile,
  heartbeatFile,
  htmlSnapshotDir,
  debugSaveFilteredHtml: bool('DEBUG_SAVE_FILTERED_HTML', false),
  logLevel: str('LOG_LEVEL', 'info'),
  selectors: {
    item: str('ITEM_SELECTOR', '.signal-row'),
    itemId: str('ITEM_ID_SELECTOR', '[data-id]'),
    title: str('TITLE_SELECTOR', '.signal-title'),
    status: str('STATUS_SELECTOR', '.signal-status'),
    coef: str('COEF_SELECTOR', '.signal-coef'),
    date: str('DATE_SELECTOR', '.signal-date')
  },
  webhookUrl: str('WEBHOOK_URL', ''),
  webhookSecret: str('WEBHOOK_SECRET', ''),
  redisUrl: str('REDIS_URL', 'redis://127.0.0.1:6379'),
  backendInternalUrl: str('BACKEND_INTERNAL_URL', ''),
  parserInternalSecret: str('PARSER_INTERNAL_SECRET', ''),
  forecastOcrUrl: str('FORECAST_OCR_URL', ''),
  forecastOcrTimeoutMs: int('FORECAST_OCR_TIMEOUT_MS', 30000),
  forecastOcrEnabled: bool('FORECAST_OCR_ENABLED', true),
  notifyOnStartup: bool('NOTIFY_ON_STARTUP', false),
  forecastActiveTabs: intList('FORECAST_ACTIVE_TABS', [1, 2]).filter((tab) => tab === 1 || tab === 2),
  forecastPerPage: int('FORECAST_PER_PAGE', 40),
  forecastStartPage: int('FORECAST_START_PAGE', 1),
  forecastMaxPages: int('FORECAST_MAX_PAGES', 10)
};
