import { NextRequest, NextResponse } from "next/server";
import { headers } from "next/headers";
import { createHmac, timingSafeEqual } from "crypto";
import { evaluatePayload, decodePayload, RemoteConfigManager, registerJti } from "@intelvisual/core";
import type { ReplayCacheStore } from "@intelvisual/core";
import { VerificationResult, ShieldThresholds, RemoteShieldConfig } from "@intelvisual/types";
import { DEFAULT_SHADOW_SHIELD_CONFIG, VERSION } from "./constants";

export { DEFAULT_SHADOW_SHIELD_CONFIG, VERSION };

export interface ServerVerifyOptions {
  thresholds?: ShieldThresholds;
  secretKey?: string;
  remoteConfigUrl?: string; // URL del JSON firmado en Intelvisual
  publicKey?: string; // Clave pública para verificar la firma del Remote Config
  /** Almacén anti-replay. Preferible implementar `setIfAbsent` (atómico, tipo SET NX EX). */
  cacheStore?: ReplayCacheStore;
  /** Si es `true`, un fallo del almacén anti-replay deniega la petición (por defecto: fail-open). */
  failClosedOnCacheError?: boolean;
  /** Acepta allowedDomains/disabledDomains aunque la firma remota (v1) no los cubra. Por defecto `false`. */
  allowUnsignedDomainLists?: boolean;
  /**
   * Confiar en cabeceras de proxy (`x-forwarded-for`) para la IP de telemetría. Por defecto `true`
   * para mantener compatibilidad; ponlo a `false` si la app no está detrás de un proxy de confianza.
   */
  trustProxyHeaders?: boolean;
  /** Cabecera concreta con la IP real (p. ej. `cf-connecting-ip`). Tiene prioridad sobre las demás. */
  ipHeader?: string;
  eventsUrl?: string; // URL para enviar bloqueos a Intelvisual
  domain?: string; // Dominio del sitio para reporte de ataques
  /**
   * Si es `true`, cuando no se recibe token de comportamiento (SDK no inicializado a tiempo)
   * se permite la petición con un score de riesgo bajo (Fail-Open) en lugar de bloquear.
   * Útil en formularios de contacto donde priorizar la conversión sobre la seguridad estricta.
   * Por defecto: `false` (modo estricto — cualquier petición sin token se deniega).
   */
  allowMissingToken?: boolean;
}

const DEFAULT_THRESHOLDS = DEFAULT_SHADOW_SHIELD_CONFIG.thresholds;

/**
 * Extrae metadatos de red (IP, UA, Dominio) de las cabeceras de la petición actual.
 */
async function getRequestMetadata(opts?: { trustProxyHeaders?: boolean; ipHeader?: string }) {
  try {
    const h = await headers();
    let ip: string | null = null;
    if (opts?.ipHeader) {
      ip = h.get(opts.ipHeader)?.split(",")[0].trim() || null;
    } else {
      // x-real-ip suele fijarlo la plataforma/proxy; x-forwarded-for es más fácil de falsificar
      ip = h.get("x-real-ip");
      if (!ip && opts?.trustProxyHeaders !== false) {
        ip = h.get("x-forwarded-for")?.split(",")[0].trim() || null;
      }
    }
    const userAgent = h.get("user-agent") || "unknown";
    const domain = h.get("host") || "unknown";
    return { ip: ip || "unknown", userAgent, domain };
  } catch (e) {
    return { ip: "unknown", userAgent: "unknown", domain: "unknown" };
  }
}

/**
 * Valida un token de telemetría de comportamiento enviado desde el cliente
 * y evalúa su nivel de riesgo.
 */
export async function verifyAntiBot(
  token: string | null | undefined,
  options?: ServerVerifyOptions
): Promise<VerificationResult> {
  let thresholds = options?.thresholds || DEFAULT_THRESHOLDS;
  let remoteConfig: RemoteShieldConfig | null = null;

  // 0. Resolver Configuración Remota (Intelvisual)
  const remoteConfigUrl = options?.remoteConfigUrl !== undefined
    ? options.remoteConfigUrl
    : ((globalThis as any).process?.env?.NEXT_PUBLIC_SHADOW_SHIELD_CONFIG_URL ||
       DEFAULT_SHADOW_SHIELD_CONFIG.configUrl);
    
  const publicKey = options?.publicKey || 
    (globalThis as any).process?.env?.SHADOW_SHIELD_PUBLIC_KEY ||
    (globalThis as any).process?.env?.NEXT_PUBLIC_SHADOW_SHIELD_PUBLIC_KEY;

  if (remoteConfigUrl) {
    const manager = RemoteConfigManager.getInstance();
    remoteConfig = await manager.getConfig(
      remoteConfigUrl,
      publicKey,
      thresholds,
      { allowUnsignedDomainLists: options?.allowUnsignedDomainLists }
    );

    // Si hay config remota y estamos en Managed Mode, sobreescribimos los thresholds
    if (remoteConfig && remoteConfig.managed) {
      thresholds = remoteConfig.thresholds;
    }
  }

  // 0.1 Control de Flota Activo: Desactivar protección si el dominio no está autorizado en el Command Center
  const { ip, userAgent, domain: detectedDomain } = await getRequestMetadata({ trustProxyHeaders: options?.trustProxyHeaders, ipHeader: options?.ipHeader });
  const rawDomain = options?.domain || detectedDomain || "";
  const cleanDomain = rawDomain
    .toLowerCase()
    .replace(/^https?:\/\//, "")
    .replace(/^www\./, "")
    .split("/")[0]
    .split(":")[0]
    .trim();

  const isLocalDev =
    !cleanDomain ||
    cleanDomain === "unknown" ||
    cleanDomain === "localhost" ||
    cleanDomain === "127.0.0.1" ||
    cleanDomain.endsWith(".local");

  if (!isLocalDev && remoteConfig) {
    const isExplicitlyDisabled = Array.isArray(remoteConfig.disabledDomains) &&
      remoteConfig.disabledDomains.some((d) => d === cleanDomain || cleanDomain.endsWith(`.${d}`));

    const hasAllowList = Array.isArray(remoteConfig.allowedDomains) && remoteConfig.allowedDomains.length > 0;
    const isAllowed = !hasAllowList || remoteConfig.allowedDomains!.some(
      (d) => d === cleanDomain || cleanDomain.endsWith(`.${d}`)
    );

    if (isExplicitlyDisabled || !isAllowed) {
      console.warn(`[Shadow Shield] Protección desactivada remotamente por Command Center para dominio no autorizado: ${cleanDomain}`);
      return {
        score: 0,
        action: "allow",
        reasons: ["Protección desactivada remotamente: Dominio no autorizado en Command Center"],
        confidence: 1.0
      };
    }
  }

  if (!token) {
    if (options?.allowMissingToken) {
      // Fail-Open: El SDK del cliente puede no haberse inicializado a tiempo (hidratación lenta).
      // Se permite la petición con un score de riesgo bajo para no bloquear usuarios legítimos.
      // El formulario sigue procesándose, pero se registra como señal sospechosa baja.
      console.warn("[Shadow Shield] Token ausente — Fail-Open activado. Petición permitida con score de riesgo bajo.");
      return {
        score: 0.40,
        action: "allow",
        reasons: ["Token de telemetría ausente — Fail-Open (allowMissingToken=true)"],
        confidence: 0.5
      };
    }
    // Si no hay token de comportamiento, es un bot que omitió la telemetría por completo
    return {
      score: 1.0,
      action: "deny",
      reasons: ["Falta de token de telemetría de comportamiento (omisión de SDK)"],
      confidence: 1.0
    };
  }

  try {
    const payload = decodePayload(token);

    // 1. Verificación de Firma (HMAC). Si se configura secretKey la firma es OBLIGATORIA:
    // omitirla ya no permite saltarse la comprobación.
    if (options?.secretKey) {
      const provided = payload.signature;
      const dataToSign = JSON.stringify({
        id: payload.id,
        jti: payload.jti,
        timestamp: payload.timestamp,
        metrics: payload.metrics
      });
      const expected = createHmac("sha256", options.secretKey).update(dataToSign).digest("hex");
      const a = Buffer.from(provided ?? "", "utf8");
      const b = Buffer.from(expected, "utf8");
      if (!provided || a.length !== b.length || !timingSafeEqual(a, b)) {
        return {
          score: 1.0,
          action: "deny",
          reasons: ["Firma de telemetría ausente o inválida (Tampering detectado)"],
          confidence: 1.0
        };
      }
    }

    // 2. Prevención de Replay Attacks (JTI)
    if (options?.cacheStore) {
      if (!payload.jti) {
        return {
          score: 1.0,
          action: "deny",
          reasons: ["Token sin identificador único (JTI faltante)"],
          confidence: 1.0
        };
      }

      const jtiState = await registerJti(options.cacheStore, payload.jti, 600);
      if (jtiState === "replayed") {
        return {
          score: 1.0,
          action: "deny",
          reasons: ["Replicación de token detectada (Replay Attack)"],
          confidence: 1.0
        };
      }
      if (jtiState === "error") {
        if (options.failClosedOnCacheError) {
          return {
            score: 1.0,
            action: "deny",
            reasons: ["Almacén anti-replay no disponible (fail-closed)"],
            confidence: 1.0
          };
        }
        console.warn("[Shadow Shield SRE Alert] Fallo en la caché de anti-replay. Fail-Open activado.");
      }
    }

    const result = evaluatePayload(payload, thresholds);
    
    // Inyectar telemetría original en el resultado para el Centro de Mando
    result.telemetry = payload.metrics;

    // 5. Telemetría Automática (Incident Reporting) v1.6.0
    const eventsUrl = options?.eventsUrl || 
      (globalThis as any).process?.env?.SHADOW_SHIELD_EVENTS_URL || 
      DEFAULT_SHADOW_SHIELD_CONFIG.eventsUrl;
    
    if (eventsUrl) {
      // Intento de reporte asíncrono "fire and forget"
      try {
        fetch(eventsUrl, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            domain: options?.domain || detectedDomain,
            action: result.action,
            score: result.score,
            reasons: result.reasons,
            telemetry: result.telemetry,
            userAgent,
            ip,
            timestamp: Date.now()
          })
        }).catch(() => {});
      } catch (e) {
        // Ignorar errores de red en telemetría para no romper la experiencia de usuario
      }
    }

    // 3. Post-procesamiento según Modo Remoto
    if (remoteConfig?.mode === "silent" && result.action === "deny") {
      // En modo silent, degradamos el bloqueo duro a un rechazo silencioso (shadow_reject)
      return {
        ...result,
        action: "shadow_reject",
        reasons: [...result.reasons, "Modo SILENT activo: Bloqueo degradado a Shadow Reject"]
      };
    }

    return result;
  } catch (error) {
    return {
      score: 1.0,
      action: "deny",
      reasons: ["Firma o token de telemetría manipulado o corrupto"],
      confidence: 1.0
    };
  }
}

export interface ProxyShieldConfig {
  thresholds?: ShieldThresholds;
  /** Opciones adicionales de verificación (cacheStore anti-replay, secretKey, publicKey, etc.). */
  verifyOptions?: Omit<ServerVerifyOptions, "thresholds">;
  onShadowReject?: (request: NextRequest, result: VerificationResult) => Promise<void> | void;
  onDeny?: (request: NextRequest, result: VerificationResult) => Promise<NextResponse> | NextResponse;
  onChallenge?: (request: NextRequest, result: VerificationResult) => Promise<NextResponse> | NextResponse;
}

/**
 * Crea una función Proxy compatible con Next.js 16+ (fichero `proxy.ts`)
 * para interceptar y verificar solicitudes maliciosas.
 */
export function createProxyShield(config?: ProxyShieldConfig) {
  const thresholds = config?.thresholds || DEFAULT_THRESHOLDS;

  return async function proxy(request: NextRequest) {
    // Solo interceptar métodos que muten datos (POST, PUT, DELETE)
    const method = request.method;
    if (method !== "POST" && method !== "PUT" && method !== "DELETE") {
      return NextResponse.next();
    }

    // El token de comportamiento puede viajar en un Header personalizado
    const token = request.headers.get("x-shadow-token");
    
    // Si la ruta contiene un formulario con multipart/form-data, podríamos revisar opcionalmente,
    // pero el header es la opción más limpia para peticiones API.
    const verification = await verifyAntiBot(token, { ...config?.verifyOptions, thresholds });

    if (verification.action === "deny") {
      if (config?.onDeny) {
        return config.onDeny(request, verification);
      }
      return NextResponse.json(
        { success: false, error: "Solicitud bloqueada por políticas de seguridad de red" },
        { status: 403 }
      );
    }

    if (verification.action === "shadow_reject") {
      if (config?.onShadowReject) {
        await config.onShadowReject(request, verification);
      }
      
      // Shadow Rejection: Hacemos creer al bot que el envío fue exitoso,
      // pero devolvemos una respuesta simulada y abortamos silenciosamente.
      return NextResponse.json(
        { success: true, shadow: true, message: "Operación procesada con éxito" },
        { status: 200 }
      );
    }

    if (verification.action === "challenge" && config?.onChallenge) {
      return config.onChallenge(request, verification);
    }

    // Permitir continuar si es humano o cumple los umbrales
    const response = NextResponse.next();
    response.headers.set("x-shadow-verified", "true");
    response.headers.set("x-shadow-action", verification.action);
    response.headers.set("x-shadow-score", verification.score.toString());
    if (verification.action === "challenge") {
      response.headers.set("x-shadow-challenge", "true");
    }

    return response;
  };
}

/**
 * Wrapper de alto nivel para proteger Server Actions de forma granular y elegante.
 */
export function withAntiBot<T, R>(
  action: (data: T, verification: VerificationResult) => Promise<R>,
  options?: ServerVerifyOptions & {
    onShadowRejectFallback?: () => Promise<R> | R;
  }
) {
  return async function (data: T, shadowToken: string | null | undefined): Promise<R> {
    const verification = await verifyAntiBot(shadowToken, options);

    if (verification.action === "deny") {
      throw new Error("Solicitud bloqueada: Comportamiento anómalo detectado.");
    }

    if (verification.action === "shadow_reject") {
      if (options?.onShadowRejectFallback) {
        return options.onShadowRejectFallback();
      }
      // Por defecto, simulamos éxito devolviendo un objeto vacío o genérico tipado
      return { success: true, message: "Acción completada con éxito (simulada)" } as unknown as R;
    }

    return action(data, verification);
  };
}

/**
 * Verifica la licencia del producto actual contra el Command Center de Intelvisual.
 * Implementa el flujo Zero-Config: no requiere clave manual, se basa en el dominio
 * y en la presencia activa del Shadow Shield.
 */
export async function verifyLicense(productId: string, options?: { domain?: string }) {
  // Bypass automático para entornos de desarrollo local
  const rawDomain = options?.domain || 
    (typeof globalThis !== 'undefined' ? (globalThis as any).process?.env?.NEXT_PUBLIC_VERCEL_URL || '' : '');
  const cleanDomain = rawDomain
    .toLowerCase()
    .replace(/^https?:\/\//, '')
    .split('/')[0]
    .split(':')[0];

  const nodeEnv = (typeof globalThis !== 'undefined' ? (globalThis as any).process?.env?.NODE_ENV : undefined) || 'development';
  const isLocalHost = cleanDomain === 'localhost' || cleanDomain === '127.0.0.1' || cleanDomain.endsWith('.local');
  if (nodeEnv !== 'production' && isLocalHost) {
    console.info(`[Shadow Shield] Entorno de desarrollo detectado (${cleanDomain}). Licencia omitida — bypass automático.`);
    return {
      valid: true,
      status: 'valid',
      licenseId: 'dev-localhost',
      planId: 'development',
      features: { shadow_shield: true },
      shieldStatus: 'active',
      expires_in: 86400,
      domain: cleanDomain,
      isDevelopment: true
    };
  }

  try {
    const intelvisualUrl = (globalThis as any).process?.env?.NEXT_PUBLIC_INTELVISUAL_URL || 
                          DEFAULT_SHADOW_SHIELD_CONFIG.configUrl.split('/api')[0];
    
    const response = await fetch(`${intelvisualUrl}/api/license/validate-by-domain`, {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'x-shadow-version': VERSION
      },
      body: JSON.stringify({ 
        productId,
        domain: options?.domain
      }),
      cache: 'no-store'
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      return { 
        valid: false, 
        error: errorData.error || `HTTP Error ${response.status}`,
        status: 'error' 
      };
    }

    return await response.json();
  } catch (error) {
    console.error("[Shadow Shield] License verification failed:", error);
    return { 
      valid: false, 
      error: "No se pudo conectar con el servidor de licencias",
      status: 'connection_error'
    };
  }
}
