use std::{io::Read, sync::LazyLock};

use common::{
    cryptography::{rsa_encrypt, rsa_sign},
    util,
};
use data::{
    CdnDesignData, CdnDispatchData, CdnGameRes, CdnSilenceData, DispatchExt, GlobalDispatchData,
    RegionExtension, RegionSwitchFunc, ServerDispatchData, ServerGateway, ServerListInfo,
    VersionFileInfo,
};

use crate::SdkState;

use super::{data, get, json, Json, Router, Value};

static CLIENT_SECRET_KEY: LazyLock<Box<[u8]>> = LazyLock::new(|| {
    let mut buf = Vec::new();
    util::open_secret_key()
        .expect("Failed to open secret key file")
        .read_to_end(&mut buf)
        .unwrap();

    buf.into_boxed_slice()
});

pub fn routes() -> Router<SdkState> {
    Router::new()
        .route("/query_dispatch", get(query_dispatch))
        .route("/query_gateway", get(query_gateway))
}

async fn query_dispatch() -> Json<GlobalDispatchData> {
    tracing::info!("query_dispatch");

    Json(GlobalDispatchData {
        retcode: 0,
        region_list: vec![ServerListInfo {
            area: 5,
            biz: String::from("nap_global"),
            name: String::from("dev_ru01"),
            dispatch_url: String::from("http://127.0.0.1:21000/query_gateway"),
            env: 2,
            is_recommend: true,
            title: String::from("ReversedRooms"),
            retcode: 0,
            ..Default::default()
        }],
        ..Default::default()
    })
}

async fn query_gateway() -> Json<Value> {
    tracing::info!("query_gateway");

    let data = ServerDispatchData {
        cdn_conf_ext: CdnDispatchData {
            design_data: CdnDesignData {
                base_url: String::from("https://autopatchcn.juequling.com/design_data/beta_live/output_3274043_3a9c953df1/client/"),
                data_revision: String::from("3274043"),
                md5_files: serde_json::to_string(&vec![VersionFileInfo {
                    file_name: String::from("data_version"),
                    file_size: 2181,
                    file_md5: String::from("2162869895617174747"),
                }]).unwrap(),
            },
            game_res: CdnGameRes {
                audio_revision: String::from("3256924"),
                base_url: String::from("https://autopatchcn.juequling.com/game_res/beta_live/output_3274043_3a9c953df1/client/"),
                branch: String::from("beta_live"),
                md5_files: serde_json::to_string(&vec![
                    VersionFileInfo {
                        file_name: String::from("res_version"),
                        file_size: 2019033,
                        file_md5: String::from("17192384088930370167"),
                    },
                    VersionFileInfo {
                        file_name: String::from("audio_version"),
                        file_size: 30458,
                        file_md5: String::from("9047433609448221050"),
                    },
                    VersionFileInfo {
                        file_name: String::from("base_revision"),
                        file_size: 18,
                        file_md5: String::from("17928040784563867653"),
                    },
                ]).unwrap(),
                res_revision: String::from("3274043"),
                },
            silence_data: CdnSilenceData {
                base_url: String::from("https://autopatchcn.juequling.com/design_data/beta_live/output_3274043_3a9c953df1/client_silence/"),
                md5_files: serde_json::to_string(&vec![VersionFileInfo {
                    file_name: String::from("silence_version"),
                    file_size: 256,
                    file_md5: String::from("13484307500875203278"),
                }]).unwrap(),
                silence_revision: String::from("3267457"),
            },
            pre_download: None,
            },
        client_secret_key: rbase64::encode(&CLIENT_SECRET_KEY),
        ext: DispatchExt {
            social_entrance_red_dot: 1,
            disable_pay: 1,
            only_goods_platform: 1,
            ..Default::default()
        },
        gateway: Some(ServerGateway {
            ip: String::from("127.0.0.1"),
            port: 20501,
        }),
        region_ext: RegionExtension {
            exchange_url: String::from(
                "https://public-operation-nap.hoyoverse.com/common/apicdkey/api/exchangeCdkey",
            ),
            func_switch: RegionSwitchFunc {
                disable_frequent_attempts: 1,
                enable_gacha_mobile_console: 1,
                enable_notice_mobile_console: 1,
                is_kcp: 0,
                ..Default::default()
            },
            pgc_webview_method: 1,
            ..Default::default()
        },
        region_name: String::from("dev_ru01"),
        retcode: 0,
        title: String::from("ReversedRooms"),
        ..Default::default()
    };

    let data = serde_json::to_string(&data).unwrap();

    Json(json!({
        "content": rbase64::encode(&rsa_encrypt(data.as_bytes())),
        "sign": rbase64::encode(&rsa_sign(data.as_bytes())),
    }))
}
