import path from "node:path";
import { fileURLToPath } from "node:url";

const runnerDirectory = path.dirname(fileURLToPath(import.meta.url));

export const PROJECT_DIRECTORY = path.resolve(runnerDirectory, "..");
export const LOCAL_DATA_DIRECTORY = path.join(
  PROJECT_DIRECTORY,
  ".local-data",
);
export const BROWSER_PROFILE_DIRECTORY = path.join(
  LOCAL_DATA_DIRECTORY,
  "browser-profile",
);
export const RUNS_DIRECTORY = path.join(LOCAL_DATA_DIRECTORY, "runs");

export const DASHBOARD_URL =
  "https://qpmcn.zhuanspirit.com/#/data-manage/n-specific_conversion";

function getChromeExecutable() {
  if (process.env.NT_CHROME_EXECUTABLE) {
    return process.env.NT_CHROME_EXECUTABLE;
  }

  if (process.platform === "darwin") {
    return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
  }

  if (process.platform === "win32") {
    const candidates = [
      process.env.LOCALAPPDATA &&
        path.join(
          process.env.LOCALAPPDATA,
          "Google",
          "Chrome",
          "Application",
          "chrome.exe",
        ),
      process.env.PROGRAMFILES &&
        path.join(
          process.env.PROGRAMFILES,
          "Google",
          "Chrome",
          "Application",
          "chrome.exe",
        ),
      process.env["PROGRAMFILES(X86)"] &&
        path.join(
          process.env["PROGRAMFILES(X86)"],
          "Google",
          "Chrome",
          "Application",
          "chrome.exe",
        ),
    ].filter(Boolean);

    return candidates[0];
  }

  return "google-chrome";
}

export const CHROME_EXECUTABLE = getChromeExecutable();

export const RUNNER_HOST = "127.0.0.1";
export const RUNNER_PORT = 4318;

export const CATEGORY_CONFIG = {
  billiards: {
    key: "billiards",
    name: "台球",
    defaultUnitPrice: 2000,
  },
  cycling: {
    key: "cycling",
    name: "骑行",
    defaultUnitPrice: 4000,
  },
};

export const DIMENSION_CONFIG = {
  sop: {
    key: "sop",
    name: "SOP",
    dashboardTitle: "广告话术",
    sheetName: "广告话术",
  },
  sku: {
    key: "sku",
    name: "SKU",
    dashboardTitle: "投放品类",
    sheetName: "投放品类",
  },
};

export function formatLocalDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

export function getPastTwoCompleteMonths(referenceDate = new Date()) {
  const end = new Date(
    referenceDate.getFullYear(),
    referenceDate.getMonth(),
    0,
  );
  const start = new Date(end.getFullYear(), end.getMonth() - 1, 1);

  return {
    start: formatLocalDate(start),
    end: formatLocalDate(end),
  };
}
