function parseBoolean(v, defaultValue) {
  if (v == null || v === '') return defaultValue;
  const s = String(v).toLowerCase().trim();
  if (['1', 'true', 'yes', 'y', 'on'].includes(s)) return true;
  if (['0', 'false', 'no', 'n', 'off'].includes(s)) return false;
  return defaultValue;
}

function parseNumber(v, defaultValue) {
  if (v == null || v === '') return defaultValue;
  const n = Number(v);
  return Number.isFinite(n) ? n : defaultValue;
}

function parseCliArgs(argv) {
  const out = {
    headless: undefined,
    dryRun: false,
    limit: undefined,
    offset: undefined,
    onlyMarket: undefined,
    logLevel: undefined,
    browser: undefined
  };

  const valueFlags = new Set(['--limit', '--offset', '--only']);
  let skipNext = false;

  for (let i = 0; i < argv.length; i++) {
    if (skipNext) {
      skipNext = false;
      continue;
    }
    const a = argv[i];

    if (a === '--headless') out.headless = true;
    else if (a === '--headed') out.headless = false;
    else if (a === '--dry-run') out.dryRun = true;
    else if (a.startsWith('--limit=')) out.limit = parseNumber(a.split('=')[1], undefined);
    else if (a === '--limit') {
      out.limit = parseNumber(argv[i + 1], undefined);
      skipNext = true;
    } else if (a.startsWith('--offset=')) out.offset = parseNumber(a.split('=')[1], undefined);
    else if (a === '--offset') {
      out.offset = parseNumber(argv[i + 1], undefined);
      skipNext = true;
    } else if (a.startsWith('--only=')) out.onlyMarket = a.split('=')[1];
    else if (a === '--only') {
      out.onlyMarket = argv[i + 1];
      skipNext = true;
    } else if (a.startsWith('--log-level=')) out.logLevel = a.split('=')[1];
    else if (!a.startsWith('-') && !out.browser) {
      const b = a.toLowerCase();
      if (b === 'yandex' || b === 'chrome' || b === 'google') out.browser = b === 'google' ? 'chrome' : b;
    }
  }

  return out;
}

function normalizeSheetId(value) {
  const s = String(value || '').trim();
  const m = s.match(/\/spreadsheets\/d\/([a-zA-Z0-9_-]+)/);
  return m ? m[1] : s;
}

function getConfigFromEnv(cli) {
  const sheetId = normalizeSheetId(process.env.SHEET_ID || '');

  const colLink = process.env.COL_LINK || 'Link';
  const colPrice = process.env.COL_PRICE || 'Price';
  const colPriceClub = process.env.COL_PRICE_CLUB || 'PriceClub';
  const colUpdatedAt = process.env.COL_UPDATED_AT || 'UpdatedAt';

  const accessServerUrl = (process.env.ACCESS_SERVER_URL || '').trim().replace(/\/$/, '');

  const cfg = {
    sheetId,
    sheetTabTitle: (process.env.SHEET_TAB_TITLE || 'Парсер ВБ').trim(),

    accessServerUrl: accessServerUrl || undefined,

    googleCredsPath: process.env.GOOGLE_CREDENTIALS_PATH || './credentials.json',
    googleServiceAccountEmail: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL || '',
    googlePrivateKey: process.env.GOOGLE_PRIVATE_KEY || '',

    updateIntervalHours: parseNumber(process.env.UPDATE_INTERVAL_HOURS, 1),
    runContinuous: parseBoolean(process.env.RUN_CONTINUOUS, false),

    // Селекторы WB: обычная цена (primary), цена по WB Клубу (accent)
    wbSelectorPrice: (process.env.WB_SELECTOR_PRICE || '').trim() || 'h2.mo-typography_color_primary',
    wbSelectorClub: (process.env.WB_SELECTOR_CLUB || '').trim() || 'h2.mo-typography_color_accent',

    userDataDir: (() => {
      const path = require('path');
      const resolve = (p) => (!p || !String(p).trim() ? undefined : path.isAbsolute(p) ? p : path.resolve(process.cwd(), p));
      const browser = cli.browser;
      if (browser === 'yandex') {
        const p = (process.env.USER_DATA_DIR_YANDEX || '').trim();
        return resolve(p);
      }
      if (browser === 'chrome') {
        const p = (process.env.USER_DATA_DIR_CHROME || '').trim();
        return resolve(p);
      }
      const p = (process.env.USER_DATA_DIR || '').trim();
      return resolve(p);
    })(),

    browserCdpUrl: (() => {
      const url = (process.env.BROWSER_CDP_URL || '').trim();
      if (url) return url;
      const port = process.env.BROWSER_CDP_PORT;
      if (port != null && String(port).trim() !== '') {
        return `http://127.0.0.1:${String(port).trim()}`;
      }
      return undefined;
    })(),

    headless: cli.headless ?? parseBoolean(process.env.HEADLESS, false),
    slowMoMs: parseNumber(process.env.SLOW_MO_MS, 50),
    delayBetweenUrlsMs: parseNumber(process.env.DELAY_BETWEEN_URLS_MS, 3000),
    navTimeoutMs: parseNumber(process.env.NAV_TIMEOUT_MS, 45000),
    priceTimeoutMs: parseNumber(process.env.PRICE_TIMEOUT_MS, 20000),

    offset: cli.offset ?? parseNumber(process.env.OFFSET, 0),
    limit: cli.limit ?? parseNumber(process.env.LIMIT, undefined),

    dryRun: cli.dryRun ?? parseBoolean(process.env.DRY_RUN, false),
    onlyMarket: cli.onlyMarket ?? (process.env.ONLY_MARKET || ''),
    logLevel: cli.logLevel ?? (process.env.LOG_LEVEL || 'info'),

    colLink,
    colPrice,
    colPriceClub,
    colUpdatedAt,

    browserChoice: cli.browser
  };

  if (!cfg.onlyMarket) cfg.onlyMarket = undefined;
  return cfg;
}

module.exports = {
  parseCliArgs,
  getConfigFromEnv
};

