export interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
}

export interface PageResult<T> {
  items: T[];
  total: number;
  page: number;
  pageSize: number;
}

export interface AdminProfile {
  id: number;
  username: string;
  name: string;
  status: number;
}

export interface DashboardStats {
  userCount: number;
  sessionCount: number;
  messageCount: number;
  aiRequestCount: number;
  knowledgeCount: number;
  inputToken: number;
  outputToken: number;
  totalToken: number;
  estimatedCost?: number | null;
  costCurrency?: string | null;
}

export interface PromptDetail {
  id: number | null;
  promptContent: string;
  changeType: "default" | "save" | "reset" | "restore";
  sourcePromptId?: number | null;
  updatedByName?: string | null;
  updatedAt?: string | null;
  charCount: number;
}

export interface PromptHistoryItem {
  id: number;
  preview: string;
  charCount: number;
  changeType: "save" | "reset" | "restore";
  sourcePromptId?: number | null;
  updatedByName: string;
  updatedAt: string;
  isCurrent: boolean;
}

export interface AdminUser {
  id: number;
  phone: string;
  name: string;
  nickname?: string | null;
  status: number;
  dailyChatLimit: number;
  dailyChatUsed: number;
  expiredAt?: string | null;
  lastLoginAt?: string | null;
  createdAt?: string | null;
  entitlement?: UserEntitlementSummary | null;
}

export interface AdminUserDetail {
  user: AdminUser;
  metrics: AdminUserMetrics;
  growthProfile?: UserGrowthProfileRecord | null;
  recentTopics: TopicSessionRecord[];
  recentHelpCards: TeacherHelpCardRecord[];
  recentShareDrafts: ShareDraftRecord[];
  recentReports: PeriodicReportRecord[];
}

export interface AdminUserMetrics {
  totalSessions: number;
  totalMessages: number;
  totalTopics: number;
  monthTopics: number;
  recentActiveDays: number;
  lastMessageAt?: string | null;
  aiRequestCount: number;
  inputToken: number;
  outputToken: number;
  totalToken: number;
  estimatedCost: number;
  costCurrency: string;
  helpCardCount: number;
  shareDraftCount: number;
  isHighFrequency: boolean;
  isInactive: boolean;
}

export interface EntitlementPlan {
  id: number;
  name: string;
  planType: "basic" | "deep" | "addon" | "teacher";
  description?: string | null;
  validityDays?: number | null;
  monthlyTopicLimit?: number | null;
  enableGrowthProfile: boolean;
  enablePeriodicReports: boolean;
  allowHelpCard: boolean;
  allowShareDraft: boolean;
  deductQuota: boolean;
  status: number;
  sortOrder: number;
  createdAt?: string | null;
  updatedAt?: string | null;
}

export interface UserEntitlementSummary {
  planId?: number | null;
  name: string;
  planType: string;
  monthlyTopicLimit?: number | null;
  monthlyTopicUsed: number;
  monthlyTopicRemaining?: number | null;
  enableGrowthProfile: boolean;
  enablePeriodicReports: boolean;
  allowHelpCard: boolean;
  allowShareDraft: boolean;
  deductQuota: boolean;
  effectiveAt?: string | null;
  expiredAt?: string | null;
  source: string;
}

export interface UserImportFailure {
  row: number;
  phone: string;
  reason: string;
}

export interface UserImportResult {
  created: number;
  updated: number;
  failed: number;
  failures: UserImportFailure[];
}

export interface SystemConfigItem {
  id: number;
  configKey: string;
  configValue: string;
  description?: string | null;
  updatedAt?: string | null;
}

export interface KnowledgeItem {
  id: number;
  name: string;
  feishuSpaceId: string;
  feishuNodeId: string;
  status: number;
  remark?: string | null;
  sourceTitle?: string | null;
  knowledgeType: "course" | "qa" | "general" | "fixed";
  lifecycleStatus: "active" | "archived";
  sourceStatus: "normal" | "error";
  sourceError?: string | null;
  currentVersionId?: number | null;
  lastSyncedAt?: string | null;
  lastPublishedAt?: string | null;
  migrationStatus: string;
  createdAt?: string | null;
  updatedAt?: string | null;
}

export interface ModelItem {
  id: number;
  provider: string;
  displayName?: string | null;
  apiType: string;
  modelName: string;
  baseUrl?: string | null;
  apiUrl: string;
  apiKeyMasked: string;
  authType: string;
  apiVersion?: string | null;
  temperature?: number | null;
  topP?: number | null;
  topK?: number | null;
  presencePenalty?: number | null;
  frequencyPenalty?: number | null;
  maxToken?: number | null;
  contextWindow?: number | null;
  streamEnabled: number;
  responseFormat?: string | null;
  extraParams?: string | null;
  remark?: string | null;
  timeoutSecond: number;
  enabled: number;
  inputPricePer1k?: number | null;
  outputPricePer1k?: number | null;
  currency: string;
  usageScenarios?: string | null;
  allowSummary: number;
  allowReport: number;
  allowFixedInfo: number;
  allowDeepChat: number;
}

export interface AgentGenerationConfig {
  temperature: number | null;
  topP: number | null;
  topK: number | null;
  presencePenalty: number | null;
  frequencyPenalty: number | null;
  maxToken: number;
  streamEnabled: number;
  reasoningVisible: number;
  responseDepth: number;
}

export interface AgentRuntimeConfig extends AgentGenerationConfig {
  modelId: number | null;
  modelName: string | null;
}

export interface AgentDebugResult {
  ok: boolean;
  message: string;
  answer: string;
  prompt: string;
  modelName?: string;
  retrieveCount?: number;
  knowledgeIds?: string;
  retrievalTrace?: Record<string, unknown>[];
  retrievalLogId?: number;
}

export interface AgentDebugStreamComplete {
  message: string;
  modelName?: string;
  retrieveCount?: number;
  knowledgeIds?: string;
  retrievalTrace?: Record<string, unknown>[];
  retrievalLogId?: number;
}

export interface KnowledgeVersion {
  id: number;
  knowledgeId: number;
  snapshotId: number;
  versionNo: number;
  status: string;
  qualityStatus: string;
  changeSummary?: Record<string, unknown> | null;
  qualityReport?: Record<string, unknown> | null;
  processingRuleVersion: string;
  generationModel?: string | null;
  createdAt: string;
  publishedAt?: string | null;
}

export interface KnowledgeManifest {
  id: number;
  versionId: number;
  purpose: string;
  applicableQuestions: string;
  inapplicableQuestions: string;
  coreTopics: string;
  entities?: string | null;
  boundaries?: string | null;
  changeLevel: string;
  confirmed: boolean;
}

export interface KnowledgeDetail {
  knowledge: KnowledgeItem;
  currentVersion?: KnowledgeVersion | null;
  manifest?: KnowledgeManifest | null;
}

export interface KnowledgeVersionContent {
  version: KnowledgeVersion;
  manifest?: KnowledgeManifest | null;
  sections: Array<{ id: number; sectionKey: string; title: string; content: string; sourceStart: number; sourceEnd: number; contentHash: string }>;
  cards: Array<Record<string, unknown>>;
}

export interface KnowledgeContentSearchItem {
  knowledgeId: number;
  knowledgeName: string;
  sourceTitle?: string | null;
  knowledgeType: "course" | "qa" | "general" | "fixed";
  knowledgeStatus: number;
  lifecycleStatus: "active" | "archived";
  sourceStatus: "normal" | "error";
  versionId: number;
  versionNo: number;
  publishedAt?: string | null;
  itemType: "section" | "card" | "chunk";
  itemTypes?: Array<"section" | "card" | "chunk">;
  itemId: number;
  sectionId: number;
  sectionKey: string;
  title: string;
  snippet: string;
  highlightTerms?: string[];
  matchedIn: Array<"title" | "content">;
  hasChunks: boolean;
  isCurrentVersion: boolean;
  canAgentUse: boolean;
}

export interface KnowledgeSyncJob {
  id: number;
  knowledgeId: number;
  mode: string;
  status: string;
  stage: string;
  progress: number;
  sourceError?: string | null;
  resultSummary?: Record<string, unknown> | null;
  createdAt: string;
  finishedAt?: string | null;
}

export interface MigrationSummary {
  total: number;
  counts: Record<string, number>;
}

export interface KnowledgeBatchUpdateResult {
  total: number;
  success: number;
  failed: number;
  results: Array<{ knowledgeId: number; ok: boolean; error?: string }>;
}

export interface KnowledgeBatchSyncResult {
  total: number;
  success: number;
  failed: number;
  results: Array<{
    knowledgeId: number;
    name?: string;
    ok: boolean;
    status?: string;
    job?: KnowledgeSyncJob;
    error?: string;
  }>;
}

export interface RetrievalLogItem {
  id: number;
  sessionId?: number | null;
  question: string;
  knowledgeCalled: boolean;
  selectedKnowledgeIds?: string | null;
  queryTerms?: string[] | null;
  status: string;
  toolCostMs?: number | null;
  totalCostMs?: number | null;
  attentionCreated: boolean;
  createdAt: string;
}

export interface AttentionItem {
  id: number;
  sessionId: number;
  messageId: number;
  userId: number;
  triggerMessage: string;
  problemSummary: string;
  triggerReason: string;
  priority: string;
  status: string;
  handlerNote?: string | null;
  createdAt: string;
}

export interface ChatRecord {
  id: number;
  userId: number;
  userPhone: string;
  userName: string;
  title: string;
  messageCount: number;
  lastMessageAt?: string | null;
  updatedAt: string;
}

export interface ChatMessageRecord {
  id: number;
  sessionId: number;
  topicSessionId?: number | null;
  userId: number;
  role: "user" | "assistant";
  content: string;
  messageStatus: string;
  tokenInput?: number | null;
  tokenOutput?: number | null;
  responseTimeMs?: number | null;
  modelId?: number | null;
  createdAt: string;
}

export interface AiLogRecord {
  id: number;
  sessionId?: number | null;
  messageId?: number | null;
  userId?: number | null;
  modelName?: string | null;
  knowledgeIds?: string | null;
  retrieveCount: number;
  retrievedChunks: RetrievedKnowledgeChunk[];
  inputToken?: number | null;
  outputToken?: number | null;
  totalToken?: number | null;
  costMs?: number | null;
  estimatedCost?: number | null;
  currency?: string | null;
  routeReason?: string | null;
  questionType?: string | null;
  knowledgeHit?: boolean;
  status: string;
  errorMessage?: string | null;
  prompt?: string | null;
  createdAt: string;
}

export interface RetrievedKnowledgeChunk {
  index: number;
  knowledgeId?: number | null;
  knowledgeName: string;
  title: string;
  content: string;
  sourceUrl?: string | null;
}

export interface ChatDetail {
  session: ChatRecord;
  messages: ChatMessageRecord[];
  messagesPage?: PageResult<ChatMessageRecord>;
  aiLogs: AiLogRecord[];
  topics?: TopicSessionRecord[];
  helpCards?: TeacherHelpCardRecord[];
  shareDrafts?: ShareDraftRecord[];
}

export interface TeacherHelpCardRecord {
  id: number;
  userId: number;
  topicSessionId: number;
  summaryId?: number | null;
  content: string;
  source: string;
  copied: boolean;
  copiedAt?: string | null;
  createdAt: string;
}

export interface ShareDraftRecord {
  id: number;
  userId: number;
  topicSessionId: number;
  summaryId?: number | null;
  content: string;
  source: string;
  copied: boolean;
  copiedAt?: string | null;
  createdAt: string;
}

export interface TopicSummaryRecord {
  id: number;
  topicSessionId: number;
  userId: number;
  summary: string;
  mainEvents?: string | null;
  emotions?: string | null;
  bodyFeelings?: string | null;
  beliefs?: string | null;
  recommendedHomework?: string | null;
  insights?: string | null;
  nextObservation?: string | null;
  modelName?: string | null;
  status: string;
  errorMessage?: string | null;
  generatedAt: string;
}

export interface UserGrowthProfileRecord {
  id: number;
  userId: number;
  profileText: string;
  recurringTopics?: string | null;
  commonEmotions?: string | null;
  bodyPatterns?: string | null;
  relationPatterns?: string | null;
  homeworkDone?: string | null;
  effectiveHomework?: string | null;
  recentProgress?: string | null;
  lastTopicSummaryId?: number | null;
  updatedBy: string;
  createdAt: string;
  updatedAt: string;
}

export interface PeriodicReportRecord {
  id: number;
  userId: number;
  reportType: "weekly" | "monthly" | "stage" | string;
  reportTypeLabel: string;
  periodStart: string;
  periodEnd: string;
  title: string;
  content: string;
  sourceSummaryIds: number[];
  sourceTopicIds: number[];
  modelName?: string | null;
  status: "success" | "failed" | "empty" | string;
  errorMessage?: string | null;
  generatedBy: string;
  generatedAt: string;
  createdAt: string;
  updatedAt: string;
}

export interface TopicSessionRecord {
  id: number;
  userId: number;
  chatSessionId: number;
  title: string;
  coreQuestion: string;
  status: string;
  messageCount: number;
  tokenInput: number;
  tokenOutput: number;
  quotaDeducted: boolean;
  recommendedHomework?: string | null;
  startedAt: string;
  endedAt?: string | null;
  createdAt?: string | null;
  updatedAt?: string | null;
  summary?: TopicSummaryRecord | null;
}

export interface QuestionInsightSummary {
  range: {
    dateFrom?: string | null;
    dateTo?: string | null;
    maxMessages: number;
  };
  summary: {
    scannedMessages: number;
    cleanedQuestions: number;
    filteredMessages: number;
    clusterCount: number;
    visibleClusterCount: number;
    minCount: number;
    cleanerVersion: string;
  };
  items: QuestionInsightCluster[];
  total: number;
  page: number;
  pageSize: number;
}

export interface QuestionInsightRefreshResult {
  processedMessages: number;
  acceptedQuestions: number;
  filteredMessages: number;
  concurrentSkips: number;
  hasMore: boolean;
  cleanerVersion: string;
}

export interface QuestionInsightCluster {
  rank: number;
  title: string;
  normalized: string;
  category: string;
  categoryLabel: string;
  count: number;
  userCount: number;
  sessionCount: number;
  aiRequestCount: number;
  noHitCount: number;
  failedCount: number;
  needsKnowledgeFollowUp: boolean;
  suggestedAction: string;
  firstSeenAt: string;
  lastSeenAt: string;
  topTerms: string[];
  variants: Array<{ text: string; count: number }>;
  samples: QuestionInsightSample[];
}

export interface QuestionInsightSample {
  messageId: number;
  sessionId: number;
  userId: number;
  userName: string;
  userPhone: string;
  raw: string;
  cleaned: string;
  createdAt: string;
}

export interface ChatRecordQuery {
  keyword?: string;
  userId?: number | null;
  status?: string;
  dateFrom?: string;
  dateTo?: string;
  page?: number;
  pageSize?: number;
}
