import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { PrismaService } from '../prisma/prisma.service';
import { AlertService } from '../common/alerting/alert.service';
import { ColdImportService } from '../modules/sync/cold-import/cold-import.service';

/**
 * DwLagMonitorService — 每小时检查 DW 增量数据滞后(W4 末)
 *
 * 输入:sync_logs 中最近一条成功的 incremental_bundle 的 cursor_after JSON
 *       例:{"fact_emr_treatment_out":"2026-05-26 15:30:00",...}
 *
 * 计算:max(cursor_after.*) vs now() → diff hours
 *   - diff <= 24h:🟢 健康
 *   - 24h < diff <= 48h:🟡 注意(DW 可能没刷新,提醒值班)
 *   - diff > 48h:🔴 异常(数据严重滞后,事件可能漏召)
 *
 * 当前实现:log + AlertService.send(webhook/钉钉)。
 *
 * 调整阈值:PAC_LAG_WARN_HOURS=24 / PAC_LAG_ERROR_HOURS=48 env
 */
@Injectable()
export class DwLagMonitorService {
  private readonly logger = new Logger(DwLagMonitorService.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly alerter: AlertService,
    private readonly coldImport: ColdImportService,
  ) {}

  /// DW 数据滞后告警 cron — env 驱动
  /// PAC_LAG_MONITOR_CRON:
  ///   不设         → 不跑(local 默认)
  ///   '0 * * * *'  → 生产 / staging 推荐(每小时检查)
  @Cron(process.env.PAC_LAG_MONITOR_CRON || '0 0 31 12 *' /* never — env not set */, {
    name: 'dw-lag-monitor',
  })
  async checkLag(): Promise<void> {
    // 全局默认(env);每宿主可在 manifest.monitoring 覆盖(上游节奏不同,一刀切会误报/漏报)
    const gWarnH = Number(process.env.PAC_LAG_WARN_HOURS ?? '24');
    const gErrorH = Number(process.env.PAC_LAG_ERROR_HOURS ?? '48');
    const now = Date.now();

    const hosts = await this.prisma.host.findMany({ select: { id: true, name: true } });
    for (const host of hosts) {
      const ops = this.coldImport.getHostOpsConfig(host.name);
      const warnH = ops.dwLagWarnHours ?? gWarnH;
      const errorH = ops.dwLagErrorHours ?? gErrorH;
      const last = await this.prisma.syncLog.findFirst({
        where: {
          hostId: host.id,
          resource: 'incremental_bundle',
          status: 'success',
          cursorAfter: { not: null },
        },
        orderBy: { startedAt: 'desc' },
      });
      if (!last?.cursorAfter) {
        this.logger.warn(`dw-lag: host=${host.name} 还没跑过增量(无 cursor)— 检查 sync-incremental cron`);
        continue;
      }
      let cursors: Record<string, string>;
      try {
        cursors = JSON.parse(last.cursorAfter) as Record<string, string>;
      } catch {
        this.logger.warn(`dw-lag: host=${host.name} cursor JSON 解析失败 — ${last.cursorAfter}`);
        continue;
      }
      const maxCursorTs = Math.max(
        ...Object.values(cursors)
          .map((v) => new Date(v).getTime())
          .filter((t) => !isNaN(t)),
      );
      const diffHours = (now - maxCursorTs) / 3_600_000;
      const tag =
        diffHours > errorH ? '🔴' :
        diffHours > warnH ? '🟡' :
        '🟢';
      const msg = `dw-lag: ${tag} host=${host.name} max_cursor=${new Date(maxCursorTs).toISOString()} lag=${diffHours.toFixed(1)}h (warn=${warnH} error=${errorH})`;
      if (diffHours > errorH) {
        this.logger.error(msg);
        await this.alerter.send({
          level: 'critical',
          title: 'DW 数据严重滞后',
          body: `增量游标已 ${diffHours.toFixed(1)} 小时未推进(阈值 ${errorH}h)— 事件可能漏召。`,
          context: { host: host.name, maxCursor: new Date(maxCursorTs).toISOString() },
        });
      } else if (diffHours > warnH) {
        this.logger.warn(msg);
        await this.alerter.send({
          level: 'warning',
          title: 'DW 数据滞后(注意)',
          body: `增量游标已 ${diffHours.toFixed(1)} 小时未推进(阈值 ${warnH}h)— DW 可能没刷新。`,
          context: { host: host.name, maxCursor: new Date(maxCursorTs).toISOString() },
        });
      } else {
        this.logger.log(msg);
      }
    }

    await this.checkPushLag(hosts, now);
  }

  /**
   * push 断流检测(纯 push 宿主的唯一"数据还活着"探针)。
   * 只对**曾经推过**的 host 生效(有 push SyncLog)—— 还没上线 push 的 host 不误报。
   * 阈值 PAC_PUSH_LAG_ERROR_HOURS(默认 26h:容忍"每日一推/每晚补推"节奏 + 2h 余量)。
   */
  private async checkPushLag(
    hosts: Array<{ id: string; name: string }>,
    now: number,
  ): Promise<void> {
    const gErrorH = Number(process.env.PAC_PUSH_LAG_ERROR_HOURS ?? '26');
    for (const host of hosts) {
      // 每宿主阈值:实时推的 host 设小(断几小时就该报),批量推的设大;缺省回退全局
      const errorH = this.coldImport.getHostOpsConfig(host.name).pushLagErrorHours ?? gErrorH;
      const lastPush = await this.prisma.syncLog.findFirst({
        where: { hostId: host.id, direction: 'push' },
        orderBy: { startedAt: 'desc' },
        select: { startedAt: true },
      });
      if (!lastPush) continue; // 从未推过 = 未上线 push,不监控
      const diffHours = (now - lastPush.startedAt.getTime()) / 3_600_000;
      if (diffHours > errorH) {
        this.logger.error(
          `push-lag: 🔴 host=${host.name} 已 ${diffHours.toFixed(1)}h 无 push(阈值 ${errorH}h)`,
        );
        await this.alerter.send({
          level: 'critical',
          title: 'push 断流:宿主推送中断',
          body:
            `host=${host.name} 最近一次 push 在 ${lastPush.startedAt.toISOString()},` +
            `已 ${diffHours.toFixed(1)} 小时无推送(阈值 ${errorH}h)— 宿主侧推送链路可能挂了,数据在漏。`,
          context: { host: host.name, lastPushAt: lastPush.startedAt.toISOString() },
        });
      } else {
        this.logger.log(`push-lag: 🟢 host=${host.name} last_push=${diffHours.toFixed(1)}h ago`);
      }
    }
  }
}
