export interface User {
  id: string;
  username: string;
  email: string;
  avatar?: string;
  credits: number;
  isAdmin: boolean;
  userType: string;
  allowedMenus?: string[] | null;
}

export interface CreditRecord {
  id: string;
  type: 'consume' | 'recharge' | 'refund';
  amount: number;
  description: string;
  createdAt: string;
}

export type Industry =
  | 'ecommerce'
  | 'education'
  | 'gaming'
  | 'medical'
  | 'finance'
  | 'realestate'
  | 'food'
  | 'travel'
  | 'tech'
  | 'other';

export const INDUSTRY_LABELS: Record<Industry, string> = {
  ecommerce: '电商',
  education: '教育',
  gaming: '游戏',
  medical: '医疗',
  finance: '金融',
  realestate: '房产',
  food: '餐饮',
  travel: '旅游',
  tech: '科技',
  other: '其他',
};

export interface Project {
  id: string;
  name: string;
  industry: Industry;
  createdAt: string;
  updatedAt: string;
}

export type AspectRatio = '16:9' | '9:16' | '1:1' | '4:3';
export type Resolution = '720p' | '1080p' | '4K';

export type GenerationStatus =
  | 'optimizing'
  | 'prompt_optimized'
  | 'generating'
  | 'completed'
  | 'failed';

export interface GenerationRecord {
  id: string;
  projectId: string;
  projectName: string;
  originalPrompt: string;
  optimizedPrompt: string;
  duration: number;
  aspectRatio: AspectRatio;
  resolution: Resolution;
  status: GenerationStatus;
  videoUrl?: string;
  creditsCost: number;
  createdAt: string;
  generatedAt?: string;
}

export interface GenerationParams {
  prompt: string;
  duration: number;
  aspectRatio: AspectRatio;
  resolution: Resolution;
}

export interface OptimizeResult {
  optimizedPrompt: string;
  creditsCost: number;
}

export interface LoginParams {
  username: string;
  password: string;
}

// ── Admin Types ──────────────────────────────────────

export interface AdminUser {
  id: string;
  username: string;
  email: string;
  phone?: string;
  credits: number;
  isActive: boolean;
  isAdmin: boolean;
  userType: string;
  frontendUserKind: 'internal' | 'external';
  createdAt: string;
  lastLoginAt?: string;
  allowedMenus?: string[] | null;
}

export interface AdminStats {
  totalUsers: number;
  totalProjects: number;
  totalGenerations: number;
  totalRecords: number;
  totalRevenue: number;
  creditsConsumedToday: number;
  todayAlipayRevenue: number;
  todayWechatRevenue: number;
  lastPeriodUsers: number;
  lastPeriodProjects: number;
  lastPeriodGenerations: number;
  lastPeriodRecords: number;
  lastPeriodRevenue: number;
  lastPeriodCreditsConsumed: number;
}

export interface PaymentStats {
    byStatus: Record<string, { count: number; amount: number }>;
    today: { paidCount: number; paidAmount: number };
    month: { paidCount: number; paidAmount: number };
    recent: PaymentOrder[];
}

export interface PaymentOrder {
  id: string;
  orderNo: string;
  userId: string;
  username?: string;
  amount: number;
  credits: number;
  paymentMethod: string;
  status: string;
  tradeNo?: string;
  paidAt?: string;
  createdAt: string;
  refundedAt?: string;
  refundAmount?: number;
}

export interface ModelConfig {
  id: string;
  name: string;
  provider: string;
  apiBase: string;
  apiKey: string;
  modelName: string;
  weight: number;
  maxTokens: number;
  temperature: number;
  isActive: boolean;
  priority: number;
}

export interface SystemConfig {
  id: string;
  key: string;
  value: string;
  description?: string;
}

export interface AdminNotification {
  id: string;
  title: string;
  content: string;
  type: string;
  isRead: boolean;
  createdAt: string;
}


export type GenerationAiGenType = 'image' | 'video';

export interface GenerationAiImageEngine {
  id: string;
  name: string;
  provider: string;
  modelName: string;
  supportedModels: string[];
  supportedSizes: Record<string, Record<string, string>>;
  defaultSize: string;
  priority: number;
}

export interface GenerationAiVideoEngine {
  id: string;
  name: string;
  provider: string;
  modelName: string;
  supportedModels: string[];
  supportedRatios: string[];
  supportedResolutions: string[];
  supportedDurations: number[];
  maxDuration: number;
  priority: number;
}

export interface GenerationAiEnginesResponse {
  engine: {
    image: GenerationAiImageEngine[];
    video: GenerationAiVideoEngine[];
  };
}

export interface GenerationAiEngineOption {
  id: string;
  name: string;
  provider: string;
  modelName: string;
  supportedModels?: string[];
  supportedRatios?: string[];
  supportedResolutions?: string[];
  supportedDurations?: number[];
  supportedSizes?: Record<string, Record<string, string>>;
  defaultSize?: string;
  maxDuration?: number;
  priority: number;
  genType: GenerationAiGenType;
}

export interface AdminGenerationRecord {
  id: string;
  userId: string;
  username: string;
  projectId: string;
  projectName: string;
  originalPrompt: string;
  optimizedPrompt: string;
  duration?: number;
  aspectRatio?: string;
  resolution?: string;
  status: 'optimizing' | 'prompt_optimized' | 'generating' | 'completed' | 'failed' | string;
  videoUrl?: string;
  videoCoverUrl?: string;
  references?: GenerationAIMediaReference[] | null;
  creditsCost: number;
  textCreditsCost: number;
  textTokensUsed: number;
  videoTokensUsed: number;
  errorMessage?: string;
  createdAt: string;
  generatedAt?: string;
  genType?: string;
  imageSize?: string;
  imageUrl?: string;
  imageTokensUsed?: number;
  imageProportion?: string;
  imagePx?: string;
}

export type GenerationAITaskStatus = 'pending' | 'generating' | 'completed' | 'failed' | string;

export interface GenerationAIMediaReference {
  url?: string;
  type?: string;
  name?: string;
  mediaUrl?: string;
  fileUrl?: string;
  mediaType?: string;
  mimeType?: string;
  [key: string]: unknown;
}

export interface GenerationAIEngineSnapshot {
  engineType?: string;
  id?: string;
  name?: string;
  provider?: string;
  modelName?: string;
  model?: string;
  supportedModels?: string[];
  defaultSize?: string;
  selectedSize?: string;
  selectedProportion?: string;
  selectedPx?: string;
  selectedRatio?: string;
  selectedResolution?: string;
  selectedDuration?: number;
  [key: string]: unknown;
}

export interface GenerationAITaskOut {
  id: string;
  sourceType?: 'chat_task' | string;
  userId?: string | null;
  userName?: string | null;
  projectId?: string | null;
  genType: GenerationAiGenType | string;
  generationMode?: string | null;
  pipelineStage?: string | null;
  status: GenerationAITaskStatus;
  originalPrompt: string;
  optimizedPrompt?: string | null;
  duration?: number | null;
  aspectRatio?: string | null;
  resolution?: string | null;
  imageSize?: string | null;
  imageProportion?: string | null;
  imagePx?: string | null;
  mediaReferences?: GenerationAIMediaReference[] | null;
  providerTaskId?: string | null;
  seedanceTaskId?: string | null;
  remoteResultUrl?: string | null;
  imageUrl?: string | null;
  videoUrl?: string | null;
  videoCoverUrl?: string | null;
  engineId?: string | null;
  engineSnapshot?: GenerationAIEngineSnapshot | null;
  creditsCost: number;
  textCreditsCost: number;
  textTokensUsed: number;
  imageTokensUsed: number;
  videoTokensUsed: number;
  retryCount: number;
  pollCount: number;
  errorMessage?: string | null;
  createdAt?: string | null;
  generatedAt?: string | null;
}

export interface GenerationAITaskListOut {
  total: number;
  items: GenerationAITaskOut[];
}

export interface GenerationAITaskQueryParams {
  genType?: GenerationAiGenType | string;
  status?: GenerationAITaskStatus;
  page?: number;
  pageSize?: number;
  userId?: string;
  userName?: string;
}



// ── Admin Replication Readonly Types ──────────────────────────────────────

export type ModuleReplicationStatus =
  | 'pending'
  | 'waiting_user'
  | 'processing'
  | 'completed'
  | 'failed'
  | 'cancelled'
  | string;

export interface ReplicationStepOut {
  id: string;
  projectId: string;
  module: string;
  stepIndex: number;
  stepCode: string;
  status: string;
  version: number;
  isCurrent: boolean;
  parentStepId?: string | null;
  sourceStepId?: string | null;
  chatTaskId?: string | null;
  input?: Record<string, any> | null;
  output?: Record<string, any> | null;
  errorMessage?: string | null;
  createdAt?: string | null;
  updatedAt?: string | null;
  completedAt?: string | null;
}

export interface ReplicationMaterialOut {
  materialStepId?: string | null;
  materialVideoUrl?: string | null;
  materialImageUrl?: string | null;
  sourceProjectName?: string | null;
  targetProjectName?: string | null;
  coreContentPoint?: string | null;
}

export interface ReplicationImageGenerationOut {
  promptStepId?: string | null;
  generateStepId?: string | null;
  prompt?: string | null;
  engineId?: string | null;
  engineName?: string | null;
  params?: Record<string, any> | null;
  chatTaskId?: string | null;
  status?: string | null;
  resultImageUrl?: string | null;
  errorMessage?: string | null;
}

export interface ReplicationVideoGenerationOut {
  promptStepId?: string | null;
  generateStepId?: string | null;
  promptSchema?: Record<string, any> | null;
  finalPrompt?: string | null;
  promptParams?: Record<string, any> | null;
  schemaConfigSnapshot?: Record<string, any> | null;
  schemaConfigSource?: string | null;
  schemaConfigVersion?: string | null;
  schemaConfigIsFallback?: boolean | null;
  engineId?: string | null;
  engineName?: string | null;
  params?: Record<string, any> | null;
  chatTaskId?: string | null;
  status?: string | null;
  resultVideoUrl?: string | null;
  resultVideoCoverUrl?: string | null;
  errorMessage?: string | null;
}

export interface ReplicationProjectDetailOut {
  id: string;
  projectId: string;
  userId?: string | null;
  userName?: string | null;
  module: string;
  title?: string | null;
  status: ModuleReplicationStatus;
  currentStepCode?: string | null;
  finalImageUrl?: string | null;
  finalVideoUrl?: string | null;
  finalVideoCoverUrl?: string | null;
  errorMessage?: string | null;
  material: ReplicationMaterialOut;
  imageGeneration: ReplicationImageGenerationOut;
  videoGeneration: ReplicationVideoGenerationOut;
  steps: ReplicationStepOut[];
  createdAt?: string | null;
  updatedAt?: string | null;
  completedAt?: string | null;
}

export interface HotOpeningTaskListItemOut {
  id: string;
  projectId: string;
  userId?: string | null;
  userName?: string | null;
  module: string;
  title?: string | null;
  status: ModuleReplicationStatus;
  currentStepCode?: string | null;
  sourceProjectName?: string | null;
  targetProjectName?: string | null;
  coreContentPoint?: string | null;
  finalImageUrl?: string | null;
  finalVideoUrl?: string | null;
  finalVideoCoverUrl?: string | null;
  errorMessage?: string | null;
  createdAt?: string | null;
  updatedAt?: string | null;
  completedAt?: string | null;
}

export interface HotOpeningTaskListOut {
  total: number;
  items: HotOpeningTaskListItemOut[];
}

export interface AdminHotOpeningTaskQueryParams {
  status?: string;
  keyword?: string;
  userId?: string;
  userName?: string;
  createdStart?: string;
  createdEnd?: string;
  page?: number;
  pageSize?: number;
}

export interface ShotTaskSetOut {
  id: string;
  userId?: string | null;
  userName?: string | null;
  title?: string | null;
  videoUrl: string;
  videoDurationSeconds: number;
  status: string;
  analysisStatus: string;
  splitStatus: string;
  originalVideoContent?: string | null;
  originalVideoCategory?: string | null;
  originalVideoAudience?: string | null;
  segmentCount: number;
  completedSegmentCount: number;
  failedSegmentCount: number;
  analysisErrorMessage?: string | null;
  splitErrorMessage?: string | null;
  createdAt?: string | null;
  updatedAt?: string | null;
}

export interface ShotAiSuggestionOut {
  index: number;
  startSecond: number;
  endSecond: number;
  durationSeconds: number;
  timeNode: string;
  content?: string | null;
  category?: string | null;
  audience?: string | null;
}

export interface ShotTaskSetDetailOut extends ShotTaskSetOut {
  aiSuggestions: ShotAiSuggestionOut[];
  analysisResultJson?: Record<string, any> | any[] | null;
}

export interface ShotTaskSetListOut {
  total: number;
  page: number;
  pageSize: number;
  items: ShotTaskSetOut[];
}

export interface AdminShotTaskSetQueryParams {
  status?: string;
  analysisStatus?: string;
  splitStatus?: string;
  keyword?: string;
  userId?: string;
  userName?: string;
  createdStart?: string;
  createdEnd?: string;
  page?: number;
  pageSize?: number;
}

export interface ShotSegmentOut {
  id: string;
  taskSetId: string;
  segmentIndex: number;
  segmentName?: string | null;
  sourceMode: string;
  startSecond: number;
  endSecond: number;
  durationSeconds: number;
  timeNode: string;
  splitStatus: string;
  analysisStatus: string;
  replicateStatus: string;
  segmentVideoUrl?: string | null;
  originalVideoContent?: string | null;
  originalVideoCategory?: string | null;
  originalVideoAudience?: string | null;
  segmentContent?: string | null;
  segmentCategory?: string | null;
  segmentAudience?: string | null;
  splitRetryCount: number;
  splitLastError?: string | null;
  analysisErrorMessage?: string | null;
  moduleProjectId?: string | null;
  moduleProjectTitle?: string | null;
  moduleProjectStatus?: string | null;
  moduleProjectCurrentStepCode?: string | null;
  createdAt?: string | null;
  updatedAt?: string | null;
}

export interface ShotSegmentDetailOut extends ShotSegmentOut {
  analysisJson?: Record<string, any> | any[] | null;
  aiSuggestionJson?: Record<string, any> | any[] | null;
}

export interface ShotSegmentListOut {
  total: number;
  page: number;
  pageSize: number;
  items: ShotSegmentOut[];
}

export interface AdminShotSegmentQueryParams {
  sourceMode?: string;
  splitStatus?: string;
  analysisStatus?: string;
  replicateStatus?: string;
  page?: number;
  pageSize?: number;
}

// ── Video Prompt Schema Config (Admin) ─────────────────────

export type VideoPromptSchemaNodeType = 'object' | 'array' | 'string' | 'number' | 'boolean' | 'flow';

export interface VideoPromptSchemaNode {
  key: string;
  label: string;
  type: VideoPromptSchemaNodeType | string;
  enabled: boolean;
  editable: boolean;
  maxLength?: number;
  value?: any;
  children?: VideoPromptSchemaNode[];
  contentKey?: string;
  contentAliases?: string[];
  itemFields?: VideoPromptFlowItemField[];
}

export interface VideoPromptFlowItemField {
  key: string;
  label: string;
  enabled: boolean;
  editable: boolean;
  maxLength?: number;
  value?: any;
}

export interface VideoPromptTimePlanSegment {
  stage: string;
  description: string;
}

export interface VideoPromptTimePlanRule {
  minDuration: number;
  maxDuration: number;
  ratios: number[];
  segments: VideoPromptTimePlanSegment[];
}

export interface VideoPromptSchemaConfigData {
  version: string;
  enabled: boolean;
  sections: VideoPromptSchemaNode[];
  timePlanRules: VideoPromptTimePlanRule[];
}

export interface VideoPromptSchemaConfigOut {
  id?: string | null;
  key: string;
  description?: string | null;
  isEnabled: boolean;
  usingDefault: boolean;
  data: VideoPromptSchemaConfigData;
  defaultData: VideoPromptSchemaConfigData;
  createdAt?: string | null;
  updatedAt?: string | null;
}

export interface VideoPromptSchemaConfigSavePayload {
  is_enabled: boolean;
  data: any;
}

export interface VideoPromptSchemaExportOut {
  version: string;
  key: string;
  isEnabled: boolean;
  data: VideoPromptSchemaConfigData;
}

export interface VideoPromptSchemaPreviewPayload {
  is_enabled: boolean;
  data: any;
  duration: number;
  aspect_ratio: string;
  resolution: string;
  frame_rate: string;
  supported_durations?: number[];
  supported_ratios?: string[];
  supported_resolutions?: string[];
}

export interface VideoPromptSchemaPreviewOut {
  schemaConfigSnapshot: Record<string, any>;
  runtimeSchema: Record<string, any>;
  timePlan: Record<string, any>[];
}


export interface AdminCreditRecordSummary {
  totalRecharge: number;
  totalConsume: number;
  totalRefund: number;
  transactionCount: number;
  generationCount: number;
  generationAttemptCount: number;
  imageGenerationCount: number;
  videoGenerationCount: number;
  imageConsume: number;
  videoConsume: number;
  textConsume: number;
  analysisConsume: number;
  totalTokens: number;
  inputTokens: number;
  outputTokens: number;
}

export interface AdminCreditRecord {
  id: string;
  userId: string;
  username?: string;
  phone?: string;
  email?: string;
  userType?: string;
  userTypeLabel?: string;
  frontendUserKind?: string;
  frontendUserKindLabel?: string;
  type: string;
  recordType: string;
  recordTypeLabel?: string;
  amount: number;
  balanceAfter: number;
  description?: string;
  relatedId?: string;
  bizKey?: string;
  refundForBizKey?: string;
  ownerType?: string;
  ownerId?: string;
  ownerDeleted?: boolean;
  ownerDeletedAt?: string;
  attemptNo?: number;
  chargeKind?: string;
  chargeKindLabel?: string;
  chargeAction?: string;
  creditSubject?: string;
  creditSubjectLabel?: string;
  mediaType?: string;
  mediaTypeLabel?: string;
  billingScene?: string;
  billingSceneLabel?: string;
  sourceModule?: string;
  sourceModuleLabel?: string;
  sourceProjectId?: string;
  sourceStepId?: string;
  sourceStepCode?: string;
  sourceStepCodeLabel?: string;
  tokenUsageId?: string;
  inputTokens: number;
  outputTokens: number;
  totalTokens: number;
  engineType?: string;
  engineId?: string;
  engineName?: string;
  engineProvider?: string;
  engineModelName?: string;
  createdAt?: string;
}

export interface AdminCreditRecordListResponse {
  items: AdminCreditRecord[];
  total: number;
  summary: AdminCreditRecordSummary;
}

export interface AdminCreditRecordQueryParams {
  page?: number;
  pageSize?: number;
  userId?: string;
  userName?: string;
  userType?: string;
  frontendUserKind?: string;
  recordType?: string;
  type?: string;
  creditSubject?: string;
  mediaType?: string;
  chargeKind?: string;
  sourceModule?: string;
  sourceStepCode?: string;
  billingScene?: string;
  startDate?: string;
  endDate?: string;
}
