/**
 * 内容审核服务 - 阿里云绿色内容检测
 * 用于书籍发布前的内容合规检查
 */

import Green20220302, * as $Green20220302 from '@alicloud/green20220302';
import { Config } from '@alicloud/openapi-client';
import { RuntimeOptions } from '@alicloud/tea-util';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// 阿里云 Green 服务 endpoint
const GREEN_ENDPOINT = 'green-cip.cn-shanghai.aliyuncs.com';

/**
 * 文本内容审核结果
 */
export interface TextCheckResult {
  safe: boolean;
  reason?: string;
  riskWords?: string[];
  code?: number;
}

/**
 * 章节审核结果
 */
export interface ChapterCheckResult {
  chapterId: number;
  title: string;
  safe: boolean;
  reason?: string;
  riskWords?: string[];
}

/**
 * 书籍审核结果
 */
export interface BookCheckResult {
  safe: boolean;
  totalChapters: number;
  checkedChapters: number;
  failedChapters: ChapterCheckResult[];
}

/**
 * 创建阿里云 Green 客户端
 * 使用与 OSS 相同的凭证（环境变量）
 */
function createGreenClient(): Green20220302 {
  const config = new Config({
    accessKeyId: process.env.OSS_ACCESS_KEY_ID || process.env.ALIBABA_CLOUD_ACCESS_KEY_ID || '',
    accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET || process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET || '',
  });
  config.endpoint = GREEN_ENDPOINT;
  return new Green20220302(config);
}

/**
 * 审核单段文本
 * @param text 要审核的文本
 * @returns 审核结果
 */
export async function checkText(text: string): Promise<TextCheckResult> {
  if (!text || text.trim() === '') {
    return { safe: true };
  }

  const client = createGreenClient();

  const textModerationPlusRequest = new $Green20220302.TextModerationPlusRequest({
    service: 'comment_detection_pro',
    serviceParameters: JSON.stringify({
      content: text,
    }),
  });

  const runtime = new RuntimeOptions({});

  try {
    const resp = await client.textModerationPlusWithOptions(textModerationPlusRequest, runtime);

    // resp.body 返回结构：
    // {
    //   code: 200,
    //   data: {
    //     result: [{ description: "未检测出风险", label: "nonLabel" }],
    //     riskLevel: "none" | "risk" | ...
    //   },
    //   message: "OK"
    // }
    const body = resp.body as any;

    // riskLevel === "none" 表示安全
    if (body?.data?.riskLevel === 'none') {
      return { safe: true };
    }

    // riskLevel === "risk" 或 "high" 表示不合规
    if (body?.data?.riskLevel === 'risk' || body?.data?.riskLevel === 'high') {
      const resultItem = body?.data?.result?.[0];
      const reason = resultItem?.description || '内容包含不合规信息';
      const riskWords = resultItem?.riskWords ? resultItem.riskWords.split(',') : [];
      return { safe: false, reason, riskWords };
    }

    // 其他情况（审核失败等）默认不阻止发布
    console.log('[ContentModeration] unexpected response:', JSON.stringify(body));
    return { safe: true };
  } catch (error: any) {
    console.error('[ContentModeration] checkText error:', error.message);
    // 网络错误等情况下，默认不阻止发布，但记录错误
    return {
      safe: true,
      reason: `审核服务异常: ${error.message}`,
    };
  }
}

/**
 * 审核单个章节的标题和正文，并写入数据库
 * @param chapter 章节信息
 * @returns 章节审核结果
 */
export async function checkChapter(chapter: {
  id: number;
  title: string;
  content: string | null;
}): Promise<ChapterCheckResult> {
  // 拼接标题 + 正文进行审核
  const textToCheck = `${chapter.title} ${chapter.content || ''}`.trim();

  const result = await checkText(textToCheck);

  // 写入数据库
  const contentCheckJson = JSON.stringify({
    passed: result.safe,
    reason: result.reason || null,
    riskWords: result.riskWords || [],
    checkedAt: new Date().toISOString(),
  });

  await prisma.bookChapter.update({
    where: { id: chapter.id },
    data: { contentCheck: contentCheckJson },
  }).catch(err => {
    console.error('[ContentModeration] failed to write contentCheck for chapter', chapter.id, err.message);
  });

  return {
    chapterId: chapter.id,
    title: chapter.title,
    safe: result.safe,
    reason: result.reason,
    riskWords: result.riskWords,
  };
}

/**
 * 审核整本书的所有章节
 * @param bookId 书籍ID
 * @returns 书籍审核结果
 */
export async function checkBook(bookId: number): Promise<BookCheckResult> {
  // 获取书籍的所有章节（所有level）
  const chapters = await prisma.bookChapter.findMany({
    where: { bookId },
    select: {
      id: true,
      title: true,
      content: true,
    },
  });

  const failedChapters: ChapterCheckResult[] = [];
  let checkedCount = 0;

  // 串行审核每个章节（阿里云接口可能有频率限制）
  for (const chapter of chapters) {
    // 只审核有内容的章节
    if (chapter.content && chapter.content.trim() !== '') {
      const result = await checkChapter(chapter);
      checkedCount++;

      if (!result.safe) {
        failedChapters.push(result);
      }
    } else {
      // 空内容章节跳过，但计数
      checkedCount++;
    }
  }

  return {
    safe: failedChapters.length === 0,
    totalChapters: chapters.length,
    checkedChapters: checkedCount,
    failedChapters,
  };
}

/**
 * 审核书籍并返回失败章节信息（用于展示）
 */
export async function checkBookWithDetails(bookId: number): Promise<{
  passed: boolean;
  failedChapters: Array<{ id: number; title: string; reason: string }>;
  errorMessage?: string;
}> {
  try {
    const result = await checkBook(bookId);

    return {
      passed: result.safe,
      failedChapters: result.failedChapters.map((fc) => ({
        id: fc.chapterId,
        title: fc.title,
        reason: fc.reason || '内容不合规',
        riskWords: fc.riskWords || [],
      })),
    };
  } catch (error: any) {
    console.error('[ContentModeration] checkBookWithDetails error:', error);
    return {
      passed: false,
      failedChapters: [],
      errorMessage: error.message,
    };
  }
}