/**
 * Sentry 初始化与 PII 过滤（ai14，P6 硬化）
 *
 * - 仅当 NEXT_PUBLIC_SENTRY_DSN 配置时初始化
 * - beforeSend 过滤学生隐私字段（姓名 / 学号 / 邮箱 / 手机号）
 * - 暴露 captureException / captureMessage 包装器，并在 window 上挂载
 *   __eduCaptureException 供 ErrorBoundary 使用
 */

import * as Sentry from "@sentry/nextjs";

/** 需要脱敏的 PII 字段名（匹配 key，不区分大小写） */
const PII_KEYS = [
  "studentname",
  "name",
  "studentno",
  "email",
  "phone",
  "mobile",
  "idcard",
];

let initialized = false;

/** 递归移除 PII 字段（返回脱敏后的副本） */
function stripPII(input: unknown): unknown {
  if (Array.isArray(input)) {
    return input.map(stripPII);
  }
  if (input && typeof input === "object") {
    const obj = input as Record<string, unknown>;
    const out: Record<string, unknown> = {};
    for (const key of Object.keys(obj)) {
      if (PII_KEYS.includes(key.toLowerCase())) {
        out[key] = "[REDACTED]";
      } else {
        out[key] = stripPII(obj[key]);
      }
    }
    return out;
  }
  return input;
}

/** 初始化 Sentry（仅在浏览器/服务端入口调用一次） */
export function initSentry(): void {
  if (initialized) return;
  const dsn = process.env.NEXT_PUBLIC_SENTRY_DSN;
  if (!dsn) return;

  Sentry.init({
    dsn,
    environment: process.env.NODE_ENV,
    tracesSampleRate: 0.1,
    beforeSend(event) {
      // 从 unknown 转换：过滤 PII 后回传事件
      const cleaned = stripPII(event);
      return cleaned as typeof event;
    },
  });
  initialized = true;

  // 挂载捕获器供 ErrorBoundary 使用
  if (typeof window !== "undefined") {
    (
      window as unknown as {
        __eduCaptureException?: (e: Error, extra?: unknown) => void;
      }
    ).__eduCaptureException = (err: Error, extra?: unknown) => {
      Sentry.captureException(
        err,
        extra !== undefined ? { extra: { detail: extra } } : undefined,
      );
    };
  }
}

/** 捕获异常（未初始化时降级为 console.error） */
export function captureException(err: unknown): void {
  if (initialized) {
    Sentry.captureException(err);
  } else if (typeof console !== "undefined") {
    console.error("[student-portal]", err);
  }
}

/** 捕获消息（未初始化时降级为 console） */
export function captureMessage(message: string): void {
  if (initialized) {
    Sentry.captureMessage(message);
  } else if (typeof console !== "undefined") {
    console.warn("[student-portal]", message);
  }
}

export default Sentry;
