/**
 * 平台规则 API 客户端
 * /api/v1/platforms
 */

import { fetchWithAuth } from "./client";

// ============================================================
// 类型定义
// ============================================================

export interface ContentLengthRule {
  min: number;
  max: number;
  recommended: number;
}

export interface StructurePreference {
  has_intro: boolean;
  has_conclusion: boolean;
  has_toc: boolean;
}

export interface TitleRule {
  min_length: number;
  max_length: number;
  avoid_patterns: string[];
  required_patterns: string[];
  case_style: string;
}

export interface TagRule {
  min_tags: number;
  max_tags: number;
  tag_style: string;
}

export interface AISensitivity {
  detection_level: string;
  banned_patterns: string[];
  banned_structures: string[];
  safe_patterns: string[];
  humanization_required: boolean;
}

export interface SensitiveWordsConfig {
  check_required: boolean;
  categories: string[];
  max_tolerance: number;
  auto_filter: boolean;
}

export interface KeywordDensity {
  min: number;
  max: number;
  recommended: number;
}

export interface SEORule {
  keyword_density: KeywordDensity;
  keyword_position: string[];
  internal_links: Record<string, number>;
}

export interface GEORule {
  citation_format: string;
  source_attribution: boolean;
  reference_style: string;
}

export interface HTMLRule {
  supported_tags: string[];
  banned_tags: string[];
  image_support: boolean;
  video_support: boolean;
  code_block_support: boolean;
}

export interface PublishRule {
  auto_publish: boolean;
  require_review: boolean;
  publish_timing: string;
}

export interface PlatformBrief {
  id: string;
  name: string;
  platform_type: string;
  priority: string;
  enabled: boolean;
}

export interface PlatformListResponse {
  platforms: PlatformBrief[];
  total: number;
}

export interface PlatformDetailResponse {
  id: string;
  name: string;
  platform_type: string;
  priority: string;
  enabled: boolean;
  content_style: string;
  content_length: ContentLengthRule;
  structure_preference: StructurePreference;
  title_rules: TitleRule;
  tag_rules: TagRule;
  ai_sensitivity: AISensitivity;
  sensitive_words: SensitiveWordsConfig;
  seo_rules: SEORule;
  geo_rules: GEORule;
  html_rules: HTMLRule;
  publish_rules: PublishRule;
  best_publish_times: string[];
  best_publish_days: string[];
  max_images: number;
}

export interface ValidationIssue {
  severity: "high" | "medium" | "low";
  message: string;
  category: string;
}

export interface ContentValidationResponse {
  is_valid: boolean;
  score: number;
  issues: ValidationIssue[];
  passed: string[];
}

export interface RuleChangeHistory {
  id: number;
  platform_id: string;
  platform_name: string;
  changed_by: string;
  change_summary: string;
  change_type: string;
  previous_rules: Record<string, unknown> | null;
  new_rules: Record<string, unknown> | null;
  created_at: string;
}

export interface RuleChangeHistoryResponse {
  history: RuleChangeHistory[];
  total: number;
}

export interface RuleUpdateRequest {
  content_style?: string;
  content_length?: ContentLengthRule;
  structure_preference?: StructurePreference;
  title_rules?: TitleRule;
  tag_rules?: TagRule;
  ai_sensitivity?: AISensitivity;
  sensitive_words?: SensitiveWordsConfig;
  seo_rules?: SEORule;
  geo_rules?: GEORule;
  html_rules?: HTMLRule;
  publish_rules?: PublishRule;
  enabled?: boolean;
}

export interface RuleUpdateResponse {
  success: boolean;
  platform_id: string;
  message: string;
  updated_at: string;
}

export interface DetectedAIPattern {
  pattern: string;
  type: string;
  severity: string;
}

export interface DetectAIPatternsResponse {
  platform_id: string;
  content_length: number;
  detected_patterns: DetectedAIPattern[];
  total_detected: number;
}

// ============================================================
// API 函数
// ============================================================

export const platformRulesApi = {
  /**
   * 获取所有平台列表
   */
  listPlatforms: async (token?: string, enabledOnly = true): Promise<PlatformListResponse> => {
    return fetchWithAuth(
      `/api/v1/platforms?enabled_only=${enabledOnly}`,
      {},
      token
    ) as Promise<PlatformListResponse>;
  },

  /**
   * 获取平台详情
   */
  getPlatformDetail: async (platformId: string, token?: string): Promise<PlatformDetailResponse> => {
    return fetchWithAuth(
      `/api/v1/platforms/${platformId}`,
      {},
      token
    ) as Promise<PlatformDetailResponse>;
  },

  /**
   * 获取规则类别列表
   */
  listRuleCategories: async (): Promise<{ categories: string[]; total: number }> => {
    return fetchWithAuth("/api/v1/platforms/categories", {}) as Promise<{
      categories: string[];
      total: number;
    }>;
  },

  /**
   * 获取平台特定类别规则
   */
  getRuleCategory: async (
    platformId: string,
    ruleCategory: string,
    token?: string
  ): Promise<{ platform_id: string; rule_category: string; rule: unknown }> => {
    return fetchWithAuth(
      `/api/v1/platforms/${platformId}/rules/${ruleCategory}`,
      {},
      token
    ) as Promise<{ platform_id: string; rule_category: string; rule: unknown }>;
  },

  /**
   * 获取平台AI配置
   */
  getAIConfig: async (
    platformId: string,
    token?: string
  ): Promise<{ platform_id: string; ai_sensitivity: AISensitivity }> => {
    return fetchWithAuth(
      `/api/v1/platforms/${platformId}/ai-config`,
      {},
      token
    ) as Promise<{ platform_id: string; ai_sensitivity: AISensitivity }>;
  },

  /**
   * 获取平台优化建议
   */
  getOptimizationTips: async (
    platformId: string,
    token?: string
  ): Promise<{
    platform_id: string;
    platform_name: string;
    content_style: string;
    tips: string[];
  }> => {
    return fetchWithAuth(
      `/api/v1/platforms/${platformId}/tips`,
      {},
      token
    ) as Promise<{
      platform_id: string;
      platform_name: string;
      content_style: string;
      tips: string[];
    }>;
  },

  /**
   * 验证内容
   */
  validateContent: async (
    platformId: string,
    content: string,
    title: string,
    token?: string
  ): Promise<ContentValidationResponse> => {
    return fetchWithAuth(
      `/api/v1/platforms/${platformId}/rules/validate`,
      {
        method: "POST",
        body: JSON.stringify({ content, title }),
      },
      token
    ) as Promise<ContentValidationResponse>;
  },

  /**
   * 检测AI写作模式
   */
  detectAIPatterns: async (
    platformId: string,
    content: string,
    token?: string
  ): Promise<DetectAIPatternsResponse> => {
    return fetchWithAuth(
      `/api/v1/platforms/${platformId}/detect-ai-patterns?content=${encodeURIComponent(content)}`,
      {},
      token
    ) as Promise<DetectAIPatternsResponse>;
  },

  /**
   * 获取规则变更历史
   */
  getRuleHistory: async (
    platformId: string,
    limit = 20,
    token?: string
  ): Promise<RuleChangeHistoryResponse> => {
    return fetchWithAuth(
      `/api/v1/platforms/${platformId}/rules/history?limit=${limit}`,
      {},
      token
    ) as Promise<RuleChangeHistoryResponse>;
  },

  /**
   * 更新平台规则
   */
  updatePlatformRules: async (
    platformId: string,
    updateData: RuleUpdateRequest,
    token?: string
  ): Promise<RuleUpdateResponse> => {
    return fetchWithAuth(
      `/api/v1/platforms/${platformId}/rules`,
      {
        method: "PUT",
        body: JSON.stringify(updateData),
      },
      token
    ) as Promise<RuleUpdateResponse>;
  },
};
