import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';

const DEFAULT_CAPTURE_STORAGE_KEY = 'work-app.token-access.registered-token';
const DEFAULT_CAPTURE_BASE_URL = 'https://preview.sm-home.cloud/';

function stripWrappingQuotes(value) {
  if (!value) {
    return value;
  }

  if (
    (value.startsWith('"') && value.endsWith('"')) ||
    (value.startsWith("'") && value.endsWith("'"))
  ) {
    return value.slice(1, -1);
  }

  return value;
}

function applyEnvFile(filePath) {
  if (!fs.existsSync(filePath)) {
    return;
  }

  const content = fs.readFileSync(filePath, 'utf8');

  for (const rawLine of content.split(/\r?\n/u)) {
    const line = rawLine.trim();

    if (!line || line.startsWith('#')) {
      continue;
    }

    const separatorIndex = line.indexOf('=');

    if (separatorIndex <= 0) {
      continue;
    }

    const key = line.slice(0, separatorIndex).trim();
    const value = stripWrappingQuotes(line.slice(separatorIndex + 1).trim());

    if (!key || process.env[key] !== undefined) {
      continue;
    }

    process.env[key] = value;
  }
}

function loadCaptureEnv(cwd = process.cwd()) {
  applyEnvFile(path.join(cwd, '.env'));
  applyEnvFile(path.join(cwd, 'etc/servers/work-server/.env'));
}

export function getCaptureRuntimeConfig(cwd = process.cwd()) {
  loadCaptureEnv(cwd);

  return {
    baseUrl:
      process.env.CAPTURE_BASE_URL?.trim() ||
      process.env.SERVER_COMMAND_TEST_URL?.trim() ||
      DEFAULT_CAPTURE_BASE_URL,
    tokenAccessStorageKey:
      process.env.CAPTURE_REGISTERED_ACCESS_STORAGE_KEY?.trim() || DEFAULT_CAPTURE_STORAGE_KEY,
    registeredAccessToken:
      process.env.CAPTURE_REGISTERED_ACCESS_TOKEN?.trim() ||
      process.env.VITE_ALLOWED_REGISTRATION_TOKEN?.trim() ||
      process.env.SERVER_COMMAND_ACCESS_TOKEN?.trim() ||
      '',
  };
}

export async function createCaptureContext(browser, options = {}) {
  const { tokenAccessStorageKey, registeredAccessToken } = getCaptureRuntimeConfig();
  const context = await browser.newContext(options);

  if (registeredAccessToken) {
    await context.addInitScript(
      ({ accessToken, storageKey }) => {
        window.localStorage.setItem(storageKey, accessToken);
      },
      {
        accessToken: registeredAccessToken,
        storageKey: tokenAccessStorageKey,
      },
    );
  }

  return context;
}
