import fs from "node:fs";
import https from "node:https";
import path from "node:path";
import { homedir } from "node:os";
import { randomInt } from "node:crypto";

const FATHOM_SITE_ID = "SGMKFBTI";
const FATHOM_ENDPOINT = "https://cdn.usefathom.com/";
const FATHOM_HOST = "https://testers.ai";
const ANALYTICS_STATE_PATH = path.join(homedir(), ".config", "carbon", "analytics.json");

const RUNTIME_EVENTS = Object.freeze({
  advise: "CARBON Help",
  framework: "CARBON Framework",
  run: "CARBON Test Run",
  "plan-view": "CARBON Execution Plan",
  browser: "CARBON Browser Test",
  vibium: "CARBON Vibium Compatibility",
  evidence: "CARBON Evidence",
  learn: "CARBON Learn",
  record: "CARBON Record Flow",
  auto: "CARBON Auto Run",
  intent: "CARBON Intent Tests",
  bake: "CARBON Import Bake-in",
  context: "CARBON Execution Context",
  flowgen: "CARBON Generate Tests",
  "select-items": "CARBON Select Built-in Tests",
  "select-flows": "CARBON Select Built-in Flows",
  "audit-library": "CARBON Audit Test Library",
  "audit-flows": "CARBON Audit Flow Library",
});

function booleanSetting(value, fallback = true) {
  if (typeof value === "boolean") return value;
  const normalized = String(value ?? "").trim().toLowerCase();
  if (["1", "true", "yes", "on"].includes(normalized)) return true;
  if (["0", "false", "no", "off"].includes(normalized)) return false;
  return fallback;
}

function readJson(file, fallback = {}) {
  try {
    return JSON.parse(fs.readFileSync(file, "utf8"));
  } catch {
    return fallback;
  }
}

export function analyticsEnabled() {
  const configPath = path.join(homedir(), ".config", "carbon", "config.json");
  const disk = readJson(configPath);
  return booleanSetting(process.env.CARBON_ANALYTICS, booleanSetting(disk.analyticsEnabled, true));
}

export function eventForInvocation(name) {
  const value = String(name || "").trim();
  if (!value) return null;
  if (/^(carbon_help|carbon_analyze_project)$/.test(value)) return "CARBON Help";
  if (/^carbon_(settings|open_settings|set_preferences|get_execution_context)$/.test(value)) return "CARBON Settings";
  if (/^carbon_(tests|list_tests|create_test|update_test|duplicate_test|archive_test|delete_test|open_test_library)$/.test(value)) return "CARBON Test Library";
  if (/^carbon_(generate|get_capabilities|get_framework_capabilities|get_specialists)$/.test(value)) return "CARBON Generate Tests";
  if (/^carbon_(browser|get_browser_capabilities|manage_browser_session)$/.test(value)) return "CARBON Browser Test";
  if (/^carbon_vibium$/.test(value)) return "CARBON Vibium Compatibility";
  if (/^carbon_(auto|open_execution_plan)$/.test(value)) return "CARBON Auto Run";
  if (/^carbon_(import_tests|manage_import_bake|upgrade)$/.test(value) || value === "ai_upgrade") return "CARBON Import Bake-in";
  if (/^carbon_(record_page_evidence|analyze_run_evidence|record_persona_feedback|record_exploration|set_test_strategy)$/.test(value)) return "CARBON Evidence";
  if (/^carbon_confidence(_init|_plan)?$/.test(value)) return "CARBON Confidence";
  if (/^carbon_(eval|eval_design_review|statistical_review)$/.test(value)) return "CARBON AI Evaluation";
  if (/^carbon_(review|skeptical_review)$/.test(value)) return "CARBON Review";
  if (/^carbon_release(_review)?$/.test(value)) return "CARBON Release";
  if (/^carbon_security_review$/.test(value)) return "CARBON Security Review";
  if (/^carbon_incident$/.test(value)) return "CARBON Incident";
  if (/^testers_(open_settings|get_account_status)$/.test(value)) return "testers.ai Settings";
  if (/^testers_(create_plan|generate_plan_items|plan)$/.test(value)) return "testers.ai Cloud Plan";
  if (/^testers_(run|run_plan|run_daily_ux|run_targeted|run_weekly_sample|run_managed_browser|run_full|run_chatbot)$/.test(value)) return "testers.ai Cloud Run";
  if (/^testers_(results|list_runs|get_results)$/.test(value)) return "testers.ai Cloud Results";
  if (/^testers_(schedule|create_schedule|list_schedules|update_schedule|delete_schedule)$/.test(value)) return "testers.ai Cloud Schedule";
  if (/^testers_(import|import_suite|propose_tests|save_tests)$/.test(value)) return "testers.ai Cloud Tests";
  if (/^testers_(get_chatbot_capabilities|validate_chatbot_project)$/.test(value)) return "testers.ai Chatbot Testing";
  return null;
}

export function eventForRuntimeCommand(command) {
  return RUNTIME_EVENTS[String(command || "").trim()] || null;
}

export function buildFathomEventUrl(eventName, page = "/carbon/plugin") {
  const params = new URLSearchParams({
    name: eventName,
    payload: "{}",
    p: page,
    h: FATHOM_HOST,
    r: "",
    sid: FATHOM_SITE_ID,
    qs: "{}",
    cid: String(randomInt(1, 100_000_001)),
  });
  return `${FATHOM_ENDPOINT}?${params.toString()}`;
}

export function trackFathomEvent(eventName, page = "/carbon/plugin") {
  if (!eventName || !analyticsEnabled()) return Promise.resolve(false);
  return new Promise((resolve) => {
    const request = https.request(buildFathomEventUrl(eventName, page), {
      method: "POST",
      headers: { "Content-Length": "0" },
      timeout: 1500,
    }, (response) => {
      response.resume();
      resolve(response.statusCode >= 200 && response.statusCode < 400);
    });
    request.on("timeout", () => request.destroy());
    request.on("error", () => resolve(false));
    request.end();
  });
}

export async function trackFirstActivation() {
  if (!analyticsEnabled()) return false;
  const state = readJson(ANALYTICS_STATE_PATH);
  if (state.firstActivationRecorded === true) return false;
  const sent = await trackFathomEvent("CARBON First Activation", "/carbon/plugin/install");
  if (!sent) return false;
  fs.mkdirSync(path.dirname(ANALYTICS_STATE_PATH), { recursive: true, mode: 0o700 });
  fs.writeFileSync(ANALYTICS_STATE_PATH, `${JSON.stringify({ firstActivationRecorded: true }, null, 2)}\n`, { mode: 0o600 });
  return true;
}
