import { sys } from 'cc';
// 使用别名导入避免命名冲突
import { BaseServiceType, HttpClient as HttpClientBrowser } from 'tsrpc-browser';
import { HttpClient as HttpClientMiniapp } from 'tsrpc-miniapp';

/**
 * 平台类型枚举
 */
export enum PlatformType {
    /** 浏览器平台 */
    Browser = "browser",
    
    /** 小程序平台 (微信、抖音、QQ等) */
    MiniApp = "miniapp",
    
    /** 未知平台 */
    Unknown = "unknown"
}

/**
 * 客户端配置接口
 */
export interface ClientConfig {
    /** 服务器地址 */
    server: string;
    
    /** 是否使用 JSON 格式 (默认 true) */
    json?: boolean;
    
    /** 超时时间(ms) */
    timeout?: number;
    
    /** 其他配置 */
    [key: string]: any;
}

/**
 * 平台适配器
 * 根据当前平台返回对应的 TSRPC 客户端实现
 * 
 * 注意: TSRPC 不同平台的库中 API 是重名的，所以使用别名导入
 * - tsrpc-browser: 用于浏览器和 XMLHttpRequest 兼容的环境
 * - tsrpc-miniapp: 用于微信、抖音、QQ 等小程序环境
 */
export class PlatformAdapter {
    private static _currentPlatform: PlatformType | null = null;
    private static _serviceProto: any = null;

    /**
     * 设置服务协议
     * @param serviceProto 从 shared 目录导入的协议定义
     */
    static setServiceProto(serviceProto: any): void {
        this._serviceProto = serviceProto;
        console.log('[PlatformAdapter] Service protocol set');
    }

    /**
     * 检测当前运行平台
     */
    static detectPlatform(): PlatformType {
        if (this._currentPlatform) {
            return this._currentPlatform;
        }

        // 检测 QQ 小游戏/小程序
        if (sys.platform === sys.Platform.WECHAT_GAME && (window as any).qq) {
            this._currentPlatform = PlatformType.MiniApp;
            return this._currentPlatform;
        }

        // 检测微信小游戏/小程序
        if (sys.platform === sys.Platform.WECHAT_GAME) {
            this._currentPlatform = PlatformType.MiniApp;
            return this._currentPlatform;
        }

        // 检测字节跳动小游戏/小程序
        if (sys.platform === sys.Platform.BYTEDANCE_MINI_GAME) {
            this._currentPlatform = PlatformType.MiniApp;
            return this._currentPlatform;
        }

        // 检测浏览器
        if (sys.isBrowser) {
            this._currentPlatform = PlatformType.Browser;
            return this._currentPlatform;
        }

        // 其他原生环境默认使用 Browser 客户端 (XMLHttpRequest 兼容)
        console.warn('[PlatformAdapter] Unknown platform, fallback to Browser client');
        this._currentPlatform = PlatformType.Browser;
        return this._currentPlatform;
    }

    /**
     * 创建对应平台的 TSRPC 客户端实例
     * @param config 客户端配置
     */
    static createClient<T extends BaseServiceType>(config: ClientConfig): HttpClientBrowser<T> | HttpClientMiniapp<T> {
        const platform = this.detectPlatform();

        // 默认配置
        const defaultConfig: ClientConfig = {
            server: config.server,
            json: true,
            timeout: config.timeout || 30000,
            ...config
        };

        // 如果设置了协议，添加到配置中
        if (this._serviceProto) {
            (defaultConfig as any).proto = this._serviceProto;
        } else {
            console.warn('[PlatformAdapter] Service protocol not set, please call setServiceProto() first');
        }

        let client: HttpClientBrowser<T> | HttpClientMiniapp<T>;

        // 根据平台创建对应的客户端
        if (platform === PlatformType.MiniApp) {
            console.log('[PlatformAdapter] Creating MiniApp client:', defaultConfig.server);
            client = new HttpClientMiniapp(this._serviceProto, defaultConfig) as HttpClientMiniapp<T>;
        } else {
            // 浏览器和其他 XMLHttpRequest 兼容环境使用 Browser 客户端
            console.log('[PlatformAdapter] Creating Browser client:', defaultConfig.server);
            client = new HttpClientBrowser(this._serviceProto, defaultConfig) as HttpClientBrowser<T>;
        }

        return client;
    }

    /**
     * 判断是否为小程序环境
     */
    static isMiniApp(): boolean {
        return this.detectPlatform() === PlatformType.MiniApp;
    }

    /**
     * 判断是否为浏览器环境
     */
    static isBrowser(): boolean {
        return this.detectPlatform() === PlatformType.Browser;
    }

    /**
     * 获取当前平台类型
     */
    static getCurrentPlatform(): PlatformType {
        if (!this._currentPlatform) {
            return this.detectPlatform();
        }
        return this._currentPlatform;
    }

    /**
     * 获取平台描述信息
     */
    static getPlatformInfo(): string {
        const platform = this.getCurrentPlatform();
        const platformName = sys.platform;
        const isMobile = sys.isMobile;
        const isNative = sys.isNative;

        return `Platform: ${platform}, OS: ${platformName}, Mobile: ${isMobile}, Native: ${isNative}`;
    }
}
