/**
 * Environment Configuration
 * ---------------------------
 * Single source of truth for all environment variables in meSEO.
 *
 * How it works:
 *   1. Detects which environment we're in (development/staging/production)
 *   2. Reads all env vars with typed accessors
 *   3. Validates required vars on first access
 *   4. Provides a simple API: env.database.url, env.auth.clerkPublishableKey, etc.
 *
 * Usage:
 *   import { env } from "@/lib/env";
 *   const dbUrl = env.database.url;
 *   if (env.isDev) console.log("Running in development");
 */

// ─── Environment detection ───────────────────────────────────────────────────

export type Environment = "development" | "staging" | "production";

/**
 * Detect the current environment.
 * Checks MESEO_ENV first (explicit override), then NODE_ENV,
 * then VERCEL_ENV (for Vercel deployments).
 */
function detectEnvironment(): Environment {
  const explicit = process.env.MESEO_ENV;
  if (explicit === "staging" || explicit === "production" || explicit === "development") {
    return explicit;
  }

  // Vercel sets this automatically
  const vercelEnv = process.env.VERCEL_ENV;
  if (vercelEnv === "production") return "production";
  if (vercelEnv === "preview") return "staging";

  // Fall back to NODE_ENV
  if (process.env.NODE_ENV === "production") return "production";

  return "development";
}

// ─── Configuration object ────────────────────────────────────────────────────

function buildConfig() {
  const environment = detectEnvironment();

  return {
    // ── Which environment ──
    environment,
    isDev: environment === "development",
    isStaging: environment === "staging",
    isProd: environment === "production",

    // ── Database ──
    database: {
      url: required("DATABASE_URL"),
    },

    // ── Auth (Clerk) ──
    auth: {
      clerkPublishableKey: required("NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY"),
      clerkSecretKey: required("CLERK_SECRET_KEY"),
      signInUrl: process.env.NEXT_PUBLIC_CLERK_SIGN_IN_URL ?? "/sign-in",
      signUpUrl: process.env.NEXT_PUBLIC_CLERK_SIGN_UP_URL ?? "/sign-up",
    },

    // ── meSEO Site Tag (tracking) ──
    tracking: {
      collectEndpoint: process.env.NEXT_PUBLIC_COLLECT_ENDPOINT ?? "/api/collect",
      trackerScriptUrl: process.env.NEXT_PUBLIC_TRACKER_SCRIPT_URL ?? "/t.js",
    },

    // ── AI Avatar ──
    ai: {
      // Phase 2: Anthropic API key for real LLM calls
      anthropicApiKey: process.env.ANTHROPIC_API_KEY ?? "",
      modelId: process.env.AI_MODEL_ID ?? "claude-sonnet-4-20250514",
    },

    // ── App URLs ──
    app: {
      url: process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000",
      apiUrl: process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:3000/api",
    },

    // ── External services (Phase 2) ──
    services: {
      googleSearchConsoleKey: process.env.GOOGLE_SEARCH_CONSOLE_KEY ?? "",
      googleAnalyticsKey: process.env.GOOGLE_ANALYTICS_KEY ?? "",
      googleBusinessProfileKey: process.env.GOOGLE_BUSINESS_PROFILE_KEY ?? "",
      bingWebmasterKey: process.env.BING_WEBMASTER_KEY ?? "",
      stripeSecretKey: process.env.STRIPE_SECRET_KEY ?? "",
      stripeWebhookSecret: process.env.STRIPE_WEBHOOK_SECRET ?? "",
    },

    // ── Feature flags (can be overridden per environment) ──
    features: {
      aiAvatarEnabled: process.env.FEATURE_AI_AVATAR !== "false",
      siteTagEnabled: process.env.FEATURE_SITE_TAG !== "false",
      billingEnabled: process.env.FEATURE_BILLING !== "false",
      debugMode: process.env.DEBUG_MODE === "true" || environment === "development",
    },
  };
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

/**
 * Get a required environment variable.
 * Throws a clear error if missing — helps catch misconfig early.
 * In development, returns a placeholder so the app can still start.
 */
function required(key: string): string {
  const value = process.env[key];
  if (value) return value;

  // During build or development, warn but don't crash
  // (env vars are set on Vercel, not in the repo files)
  console.warn(`[env] Missing required variable: ${key}`);
  return `MISSING_${key}`;
}

// ─── Export ──────────────────────────────────────────────────────────────────

/**
 * The typed environment config.
 * Access any variable: env.database.url, env.auth.clerkSecretKey, etc.
 */
export const env = buildConfig();

/**
 * Log the current environment (useful for debugging).
 * Only logs in development or when DEBUG_MODE=true.
 */
export function logEnvironment(): void {
  if (!env.features.debugMode) return;

  console.log(`[meSEO] Environment: ${env.environment}`);
  console.log(`[meSEO] App URL: ${env.app.url}`);
  console.log(`[meSEO] Database: ${env.database.url ? "configured" : "MISSING"}`);
  console.log(`[meSEO] Clerk: ${env.auth.clerkPublishableKey ? "configured" : "MISSING"}`);
  console.log(`[meSEO] AI Avatar: ${env.features.aiAvatarEnabled ? "enabled" : "disabled"}`);
  console.log(`[meSEO] Site Tag: ${env.features.siteTagEnabled ? "enabled" : "disabled"}`);
  console.log(`[meSEO] Billing: ${env.features.billingEnabled ? "enabled" : "disabled"}`);
}
