import axios from 'axios';
import { ElMessage } from 'element-plus';

// true: 使用模拟数据, false: 请求真实后端
const isMock = false; 

const api = axios.create({
  baseURL: '/api', // Nginx 将会把这个前缀代理到后端服务
  timeout: 10000,
});

// 响应拦截器
api.interceptors.response.use(
  response => response.data,
  error => {
    ElMessage.error(error.message || '网络请求失败');
    return Promise.reject(error);
  }
);

// ---- 模拟数据生成器 (用于分页列表) ----
const createMockListData = (page, pageSize, total, itemGenerator) => {
    const items = [];
    const count = Math.min(pageSize, total - (page - 1) * pageSize);
    for (let i = 0; i < count; i++) {
        items.push(itemGenerator(i + (page - 1) * pageSize));
    }
    // 模拟网络延迟
    return new Promise(resolve => setTimeout(() => {
        resolve({
            total: total,
            list: items,
        });
    }, 500));
};

// ---- API 接口定义 ----

/** 系统配置 */
export const getSystemConfig = () => isMock
    ? Promise.resolve({
        douban: { cookie: 'douban_cookie_test_value_xxxxxx' },
        skit_paths: ['/skits', '/downloads/completed'], // 现在是数组
        ptskit: { 
            url: 'https://ptskit.com', 
            cookie: 'ptskit_cookie_test_value_xxxxxx', 
            user_agent: '' 
        },
        qbittorrent: { 
            host: 'localhost', 
            port: 8080, 
            username: 'admin', 
            password: 'adminadmin' 
        },
        transmission: { 
            host: 'localhost', 
            port: 9091, 
            username: '', 
            password: '' 
        },
        emby: { 
            host: 'localhost', 
            port: 8096, 
            use_ssl: false, 
            api_key: 'emby_api_key_test' 
        },
        plex: { 
            host: 'localhost', 
            port: 32400, 
            use_ssl: false, 
            token: 'plex_token_test' 
        },
        fnos: { 
            host: 'localhost', 
            port: 1999, 
            use_ssl: false, 
            authorization: 'fnos_auth_token_test' 
        },
    })
    : api.get('/system/config');
export const saveSystemConfig = (data) => isMock ? Promise.resolve({ message: '配置保存成功！' }) : api.post('/system/config', data);
export const testConnection = (data) => isMock 
    ? new Promise(resolve => setTimeout(() => resolve({ success: true, message: `[Mock] ${data.type} 连接成功！` }), 1000))
    : api.post('/system/test_connection', data);


/** 首页 / 仪表盘 */
export const getInitialCheck = () => isMock
    ? Promise.resolve({ is_configured: true }) // <-- 修改为 false 来测试顶部的“请配置”警告条
    : api.get('/dashboard/initial_check');

export const getDashboardStats = () => isMock
    ? new Promise(resolve => setTimeout(() => resolve({
        local_skits: 2,
        fnos_items: 2,
        emby_items: 2,
        plex_items: 0,
        qb_total: 47,
        tr_total: 4,
      }), 800)) // 模拟网络延迟，让 loading 效果更明显
    : api.get('/dashboard/stats');

export const testAllComponents = () => isMock
    ? new Promise(resolve => setTimeout(() => resolve({
        douban_cookie: { status: 'success', message: 'Cookie已配置' },
        ptskit_cookie: { status: 'success', message: 'Cookie已配置' },
        local_path: { status: 'success', message: '已挂载' },
        qbittorrent: { status: 'success', message: '连接成功 v4.5.2' },
        transmission: { status: 'error', message: '连接失败: 认证错误' },
        fnos: { status: 'unconfigured', message: '未配置' },
        emby: { status: 'success', message: '连接成功' },
        plex: { status: 'unconfigured', message: '未配置' },
      }), 1500)) // 模拟一个较长的测试时间
    : api.get('/dashboard/component_statuses');


/** 本地媒体 */
export const getLocalMedia = (params) => isMock
    ? createMockListData(params.page, params.pageSize, 88, i => ({
        id: i + 1,
        title: `短剧-本地风云-${i + 1}`,
        path: `/media/短剧-本地风云-${i + 1}`,
        poster: `https://picsum.photos/seed/${i}/200/300`,
        scraped: i % 3 === 0, // 模拟刮削状态
    }))
    : api.get('/local-media', { params });

/** PTSKIT 种子 */
export const getPtskitTorrents = (params) => isMock
    ? createMockListData(params.page, params.pageSize, 123, i => ({
        id: `torrent-${i}`,
        title: `[PTSKIT] 超好看的短剧 S01 全集 ${i + 1}GB`,
        size: `${(Math.random() * 10).toFixed(2)} GB`,
        seeders: Math.floor(Math.random() * 100),
        leechers: Math.floor(Math.random() * 20),
        download_url: `https://ptskit.com/download.php?id=${i}`
    }))
    : api.get('/ptskit/torrents', { params });

/** 下载 */
export const addDownloadTask = (data) => isMock ? Promise.resolve({ message: '任务添加成功' }) : api.post('/downloader/add', data);

/** 刮削 */
export const scrapeMedia = (data) => isMock ? Promise.resolve({ message: '开始刮削' }) : api.post('/scrape', data);

/** 媒体服务器 */
export const getMediaServerLibrary = (serverType, params) => isMock
    ? createMockListData(params.page, params.pageSize, 50, i => ({
        id: `${serverType}-${i}`,
        title: `[${serverType.toUpperCase()}] 服务器上的短剧 ${i + 1}`,
        year: 2023,
        poster: `https://picsum.photos/seed/${serverType}${i}/200/300`,
    }))
    : api.get(`/${serverType}/library`, { params });
