/**
 * API abstraction layer.
 * Switches between mock data and real backend based on VITE_USE_MOCK env var.
 */
import { api, setToken, clearToken } from './client';
import * as mock from './mock';
import type {
  User, CreditRecord, Project, GenerationRecord, OptimizeParams, GenerateParams, OptimizeResult,
  Industry, IndustryConfig, AdminUser, AdminStats, ModelConfig, SystemConfig, AdminNotification,
} from '../types';
const USE_MOCK = import.meta.env.VITE_USE_MOCK === 'true';
// ── Auth ──────────────────────────────────────────────────
export async function login(username: string, password: string, captchaToken?: string, rememberMe?: boolean): Promise<User> {
  if (USE_MOCK) return mock.mockLogin({ username, password });
  const res = await api.post<{ accessToken: string; user: User }>('/auth/login', { username, password, captcha_token: captchaToken, remember_me: rememberMe || false }, false, true);
  setToken(res.accessToken);
  return res.user;
}
export async function phonelogin(phone: string, code: string): Promise<User> {
  // if (USE_MOCK) return mock.mockLogin({ username, password });
  const res = await api.post<{ accessToken: string; user: User }>('/auth/sms-login', { phone, code }, false, true);
  setToken(res.accessToken);
  return res.user;
}
export async function register(phone: string, code: string, password: string): Promise<User> {
  const res = await api.post<{ accessToken: string; user: User }>('/auth/register', { phone, code, password }, false);
  setToken(res.accessToken);
  return res.user;
}
export async function logout(): Promise<void> {
  if (USE_MOCK) return mock.mockLogout();
  await api.post('/auth/logout');
  clearToken();
}
export async function getUser(): Promise<User | null> {
  if (USE_MOCK) return mock.mockGetUser();
  try {
    return await api.get<User>('/auth/me');
  } catch {
    return null;
  }
}
export async function changePassword(oldPwd: string, newPwd: string): Promise<void> {
  if (USE_MOCK) return;
  await api.post('/auth/change-password', { old_password: oldPwd, new_password: newPwd });
}
// ── Projects ──────────────────────────────────────────────
export async function getProjects(): Promise<Project[]> {
  if (USE_MOCK) return mock.mockGetProjects();
  return api.get<Project[]>('/projects');
}
export async function createProject(name: string, industry: Industry): Promise<Project> {
  if (USE_MOCK) return mock.mockCreateProject(name, industry);
  return api.post<Project>('/projects', { name, industry });
}
export async function deleteProject(id: string): Promise<void> {
  if (USE_MOCK) return mock.mockDeleteProject(id);
  await api.delete(`/projects/${id}`);
}
// ── Generation ────────────────────────────────────────────
export interface GenerationRecordPageListOut {
  page: number;
  pageSize: number;
  total: number;
  items: GenerationRecord[];
}
export interface GetRecordsPageParams {
  projectId?: string;
  status?: string;
  page?: number;
  pageSize?: number;
  signal?: AbortSignal;
}
export async function getRecordsPage(params: GetRecordsPageParams = {}): Promise<GenerationRecordPageListOut> {
  const page = params.page && params.page > 0 ? params.page : 1;
  const pageSize = params.pageSize && params.pageSize > 0 ? params.pageSize : 10;

  if (USE_MOCK) {
    const mockRecords = await mock.mockGetGenerationRecords(params.projectId);
    const filtered = params.status
      ? mockRecords.filter((record) => record.status === params.status)
      : mockRecords;
    const start = (page - 1) * pageSize;

    return {
      page,
      pageSize,
      total: filtered.length,
      items: filtered.slice(start, start + pageSize),
    };
  }
  const query = new URLSearchParams();
  if (params.projectId) query.set('project_id', params.projectId);
  if (params.status) query.set('status', params.status);
  query.set('page', String(page));
  query.set('page_size', String(pageSize));

  return api.get<GenerationRecordPageListOut>(`/generation-records?${query.toString()}`, { signal: params.signal });
}
export async function optimizePrompt(
  projectId: string, params: OptimizeParams
): Promise<OptimizeResult> {
  if (USE_MOCK) return mock.mockOptimizePrompt(projectId, params as any);
  return api.post('/generation-records/optimize', {
    project_id: projectId,//项目id
    gen_type:params.genType,//生成类型
    prompt: params.prompt,
    duration: params.duration,
    references: params.references || null,
    idempotency_key: params.idempotencyKey || null,
    image_size: params.image_size || null,
    image_proportion: params.image_proportion || null,
    image_px: params.image_px || null,
  });
}
export async function uploadImage(file: File): Promise<{ url: string; filename: string }> {
  const form = new FormData();
  form.append('file', file);
  const token = localStorage.getItem('auth_token');
  const res = await fetch(`${import.meta.env.VITE_API_BASE || 'http://localhost:8000'}/api/generation-records/upload-image`, {
    method: 'POST',
    headers: token ? { Authorization: `Bearer ${token}` } : {},
    body: form,
  });
  if (!res.ok) throw new Error('图片上传失败');
  const data = await res.json();
  return { url: data.url, filename: data.filename };
}
export async function uploadVideo(file: File): Promise<{ url: string; filename: string }> {
  const form = new FormData();
  form.append('file', file);
  const token = localStorage.getItem('auth_token');
  const res = await fetch(`${import.meta.env.VITE_API_BASE || 'http://localhost:8000'}/api/generation-records/upload-video`, {
    method: 'POST',
    headers: token ? { Authorization: `Bearer ${token}` } : {},
    body: form,
  });
  if (!res.ok) throw new Error('视频上传失败');
  const data = await res.json();
  return { url: data.url, filename: data.filename };
}
export async function deleteUpload(url: string): Promise<void> {
  await api.post(`/generation-records/delete-file?url=${encodeURIComponent(url)}`);
}
export async function updateRecordPrompt(recordId: string, optimizedPrompt: string): Promise<void> {
  await api.put(`/generation-records/${recordId}/prompt`, { optimized_prompt: optimizedPrompt });
}
export async function generateVideo(recordId: string, params: GenerateParams): Promise<GenerationRecord> {
  if (USE_MOCK) return mock.mockGenerateVideo(recordId);
  return api.post<GenerationRecord>(`/generation-records/${recordId}/generate`, {
    aspect_ratio: params.aspectRatio,
    resolution: params.resolution,
  });
}
// ── Credits ───────────────────────────────────────────────
export async function getCredits(page = 1, pageSize = 20): Promise<{ credits: number; records: CreditRecord[]; total: number }> {
  if (USE_MOCK) {
    const data = await mock.mockGetCredits();
    return data;
  }
  const params = new URLSearchParams();
  params.set('page', String(page));
  params.set('page_size', String(pageSize));
  return api.get(`/credits?${params.toString()}`);
}
// ── Captcha ───────────────────────────────────────────────
export async function getSliderCaptcha(): Promise<{ captcha_id: string; bg_image: string; slider_image: string }> {
  if (USE_MOCK) return { captcha_id: 'mock', bg_image: '', slider_image: '' };
  return api.get('/captcha/slider', false);
}
export async function verifyCaptcha(captchaId: string, x: number): Promise<string> {
  if (USE_MOCK) return 'mock-token';
  const res = await api.post<{ token: string }>('/captcha/verify', { captcha_id: captchaId, x_offset: x }, false);
  return res.token;
}
// ── Site Info ─────────────────────────────────────────────
export async function getSiteInfo(): Promise<{ siteName: string; siteLogo: string; userAgreementUrl: string; privacyPolicyUrl: string }> {
  if (USE_MOCK) return { siteName: 'VideoGen.AI', siteLogo: '', userAgreementUrl: '', privacyPolicyUrl: '' };
  return api.get('/auth/site-info', false);
}
// ── Video Engines ─────────────────────────────────────────
export async function getVideoEngines(): Promise<{ items: { id: string; name: string; provider: string; supportedRatios: string[]; supportedResolutions: string[]; supportedDurations: number[] }[] }> {
  if (USE_MOCK) return { items: [{ id: 'mock', name: 'Seedance', provider: 'seedance', supportedRatios: ['16:9', '9:16', '1:1', '4:3', '3:4', '21:9'], supportedResolutions: ['480p', '720p', '1080p'], supportedDurations: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] }] };
  return api.get('/video-engines');
}
// 参数选择（图片）Parameters
export async function getParameters(): Promise<any[]> {
  return api.get('/image-engines');
}
// ── SMS ───────────────────────────────────────────────────
export async function sendSms(phone: string, scene: string): Promise<void> {
  if (USE_MOCK) return;
  await api.post('/sms/send', { phone, scene: scene }, false);
}
export async function verifySms(phone: string, code: string): Promise<{ token: string }> {
  if (USE_MOCK) return { token: 'mock-sms-token' };
  return api.post('/sms/verify', { phone, code }, false);
}
// ── Notifications ─────────────────────────────────────────
export async function getNotifications(page = 1, pageSize = 20, isRead?: boolean): Promise<{ items: AdminNotification[], total: number }> {
  if (USE_MOCK) {
    const items = await mock.mockGetAdminNotifications();
    return { items, total: items.length };
  }
  const params = new URLSearchParams();
  params.set('page', String(page));
  params.set('page_size', String(pageSize));
  if (isRead !== undefined) {
    params.set('is_read', String(isRead));
  }
  return api.get(`/notifications?${params.toString()}`);
}
export async function getUnreadCount(): Promise<number> {
  if (USE_MOCK) return mock.mockGetAdminNotifications().then(n => n.filter(x => !x.isRead).length);
  const res = await api.get<{ count: number }>('/notifications/unread-count');
  return res.count;
}
export async function markNotificationRead(id: string): Promise<void> {
  if (USE_MOCK) return;
  await api.put(`/notifications/${id}/read`);
}
// ── Admin ─────────────────────────────────────────────────
export async function getAdminStats(): Promise<AdminStats> {
  if (USE_MOCK) return mock.mockGetAdminStats();
  return api.get('/admin/stats');
}
export async function getAdminUsers(search?: string): Promise<AdminUser[]> {
  if (USE_MOCK) return mock.mockGetAdminUsers(search);
  const q = search ? `?search=${encodeURIComponent(search)}` : '';
  return api.get(`/admin/users${q}`);
}
export async function adjustCredits(userId: string, amount: number, description: string): Promise<void> {
  if (USE_MOCK) return mock.mockAdjustCredits(userId, amount, description);
  await api.post(`/admin/users/${userId}/credits`, { amount, description });
}
export async function toggleUserStatus(userId: string, isActive: boolean): Promise<void> {
  if (USE_MOCK) return mock.mockToggleUserStatus(userId, isActive);
  await api.put(`/admin/users/${userId}/status`, { is_active: isActive });
}
export async function getModelConfigs(): Promise<ModelConfig[]> {
  if (USE_MOCK) return mock.mockGetModelConfigs();
  return api.get('/admin/model-configs');
}
export async function saveModelConfig(config: Partial<ModelConfig> & { id?: string }): Promise<ModelConfig> {
  if (USE_MOCK) return mock.mockSaveModelConfig(config as any);
  if (config.id) return api.put(`/admin/model-configs/${config.id}`, config);
  return api.post('/admin/model-configs', config);
}
export async function deleteModelConfig(id: string): Promise<void> {
  if (USE_MOCK) return mock.mockDeleteModelConfig(id);
  await api.delete(`/admin/model-configs/${id}`);
}
export async function getSystemConfigs(): Promise<SystemConfig[]> {
  if (USE_MOCK) return mock.mockGetSystemConfigs();
  return api.get('/admin/system-configs');
}
export async function updateSystemConfig(id: string, value: string): Promise<void> {
  if (USE_MOCK) return mock.mockUpdateSystemConfig(id, value);
  await api.put(`/admin/system-configs/${id}`, { value });
}
// ── Industries ─────────────────────────────────────────────
export async function getIndustries(): Promise<IndustryConfig[]> {
  const data = await api.get<any[]>('/industries');
  return data.map((item: any) => {
    const skills = Array.isArray(item.skills) ? item.skills : [];
    const optionGroups = skills
      .filter((s: any) => s && s.type === 'option_group' && s.name && Array.isArray(s.options))
      .map((s: any) => ({ name: s.name, options: s.options }));
    return { ...item, optionGroups };
  });
}
// ── Menu Config ────────────────────────────────────────────
export async function getMenuConfigs(): Promise<any[]> {
  return api.get('/menu-configs');
}
// ── Recharge Packages ──────────────────────────────────────
export async function getRechargePackages(): Promise<any[]> {
  return api.get('/recharge-packages');
}

export async function getPaymentMethods(): Promise<{ alipay: boolean; wechat: boolean }> {
  return api.get('/payments/methods');
}

export async function createRechargeOrder(planId: string, method: string = 'wechat'): Promise<any> {
  return api.post('/payments/recharge', { plan: planId, method });
}

export async function getPaymentOrders(page = 1, pageSize = 20): Promise<{ items: any[]; total: number }> {
  const params = new URLSearchParams();
  params.set('page', String(page));
  params.set('page_size', String(pageSize));
  return api.get(`/payments/orders?${params.toString()}`);
}

export async function getPaymentOrder(orderNo: string): Promise<any> {
  return api.get(`/payments/orders/${orderNo}`);
}

export async function cancelPaymentOrder(orderNo: string): Promise<void> {
  return api.post(`/payments/orders/${orderNo}/cancel`);
}

export async function getCreditRatios(): Promise<any[]> {
  return api.get('/credits/ratios');
}
// 引擎配置
export async function getEngine(): Promise<any[]> {
  return api.get('/generation-ai/engines');
}
// ── Generation AI Tasks ────────────────────────────────────
// 创建ai生成任务
export async function createGenerationTask(params: any): Promise<any> {
  return api.post('/generation-ai/tasks', params);
}
// 获取ai生成任务列表
export async function getgen_list(Pagebreak: any): Promise<any[]> {
  return api.get('/generation-ai/tasks?page='+Pagebreak.page+'&page_size='+Pagebreak.pageSize);
}
// 获取生成任务历史记录
export async function gethistory(Pagebreak: any): Promise<any[]> {
  return api.get('/generation-ai/history'+Pagebreak);
}
// 获取生成任务历史记录子项
export async function gethistoryItems(Pagebreak: any): Promise<any[]> {
  return api.get('/generation-ai/history/'+Pagebreak);
}
// 删除ai对话历史记录
export async function deleteHistory(id: string): Promise<void> {
  await api.delete(`/generation-ai/tasks/${id}`);
}
export async function calculateCredits(): Promise<any[]> {
  return api.get('/credits/credit-ratios');
}
// 获取验证码
export async function getSendcode(phone: string): Promise<any> {
  return api.post('/sms/send', { phone });
}
export interface OAuthAppParam {
  page: number;
  pageSize: number;
  open_type?: string;
  status?: string;
  app_id?: string;
}
export interface OAuthAppList {
  page: number;
  pageSize: number;
  total: number;
  data: any[];
}
// 获取用户列表
export async function getAuthorizationList(params: OAuthAppParam): Promise<OAuthAppList> {
  const query = new URLSearchParams();
  query.set('page', String(params.page));
  query.set('page_size', String(params.pageSize));
  if (params.open_type) query.set('open_type', params.open_type);
  if (params.status) query.set('status', params.status);
  if (params.app_id) query.set('app_id', params.app_id);

  return api.get<OAuthAppList>(`/admin/user-oauth-apps/list?${query.toString()}`);
}


// 爆款开头复刻
export async function generateReplication(params: any): Promise<any> {
  return api.post('/hot-opening-replications/tasks', params);
}
// 获取爆款开头复刻任务列表
export async function getReplicationList(page: number,page_size: number): Promise<any[]> {
  return api.get(`/hot-opening-replications/tasks?page=${page}&page_size=${page_size}`);
}
// 获取爆款开头复刻任务详情
export async function getReplicationDetail(id: string): Promise<any> {
  return api.get(`/hot-opening-replications/tasks/${id}`);
}
// 第一步，生成提示词
export async function getone(projectId: string, stepId: string): Promise<any> {
  return api.post(`/hot-opening-replications/tasks/${projectId}/steps/${stepId}/generate-image-prompt`);
}

// 第二步，生成图片
export async function gettwo(projectId: string, stepId: string ,params: any): Promise<any> {
  return api.post(`/hot-opening-replications/tasks/${projectId}/steps/${stepId}/generate-image`, params);
}

// 第三步，生成视频提示词
export async function getthree(projectId: string, stepId: string ,params: any): Promise<any> {
  return api.post(`/hot-opening-replications/tasks/${projectId}/steps/${stepId}/generate-video-prompt`, params);
}
// 第四步，生成视频
export async function getfour(projectId: string, stepId: string ,params: any): Promise<any> {
  return api.post(`/hot-opening-replications/tasks/${projectId}/steps/${stepId}/generate-video`, params);
}
