use dispatch2::{DispatchQueue, DispatchQueueGlobalPriority, DispatchTime, GlobalQueueIdentifier};
use mach2::{
    kern_return::KERN_SUCCESS,
    mach_time::mach_timebase_info_data_t,
    thread_policy::{
        THREAD_EXTENDED_POLICY, THREAD_EXTENDED_POLICY_COUNT, THREAD_PRECEDENCE_POLICY,
        THREAD_PRECEDENCE_POLICY_COUNT, THREAD_TIME_CONSTRAINT_POLICY,
        THREAD_TIME_CONSTRAINT_POLICY_COUNT, thread_extended_policy_data_t,
        thread_precedence_policy_data_t, thread_time_constraint_policy_data_t,
    },
};
use rgpui::{PlatformDispatcher, Priority, RunnableMeta, RunnableVariant};
use rgpui::util::ResultExt;

use async_task::Runnable;
use objc::{
    class, msg_send,
    runtime::{BOOL, YES},
    sel, sel_impl,
};
use std::{ffi::c_void, ptr::NonNull, time::Duration};

pub(crate) struct MacDispatcher;

impl MacDispatcher {
    /// 创建新的 MacDispatcher 实例。
    pub fn new() -> Self {
        Self
    }
}

impl PlatformDispatcher for MacDispatcher {
    /// 检查当前是否在主线程上。
    fn is_main_thread(&self) -> bool {
        let is_main_thread: BOOL = unsafe { msg_send![class!(NSThread), isMainThread] };
        is_main_thread == YES
    }

    /// 将任务分发到后台线程执行。
    fn dispatch(&self, runnable: RunnableVariant, priority: Priority) {
        let context = runnable.into_raw().as_ptr() as *mut c_void;

        let queue_priority = match priority {
            Priority::RealtimeAudio => {
                panic!("RealtimeAudio priority should use spawn_realtime, not dispatch")
            }
            Priority::High => DispatchQueueGlobalPriority::High,
            Priority::Medium => DispatchQueueGlobalPriority::Default,
            Priority::Low => DispatchQueueGlobalPriority::Low,
        };

        unsafe {
            DispatchQueue::global_queue(GlobalQueueIdentifier::Priority(queue_priority))
                .exec_async_f(context, trampoline);
        }
    }

    /// 将任务分发到主线程执行。
    fn dispatch_on_main_thread(&self, runnable: RunnableVariant, _priority: Priority) {
        let context = runnable.into_raw().as_ptr() as *mut c_void;
        unsafe {
            DispatchQueue::main().exec_async_f(context, trampoline);
        }
    }

    /// 延迟指定时间后执行任务。
    fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant) {
        let context = runnable.into_raw().as_ptr() as *mut c_void;
        let queue = DispatchQueue::global_queue(GlobalQueueIdentifier::Priority(
            DispatchQueueGlobalPriority::High,
        ));
        let when = DispatchTime::NOW.time(duration.as_nanos() as i64);
        unsafe {
            DispatchQueue::exec_after_f(when, &queue, context, trampoline);
        }
    }

    /// 使用实时音频优先级生成新线程。
    fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>) {
        std::thread::spawn(move || {
            set_audio_thread_priority().log_err();
            f();
        });
    }
}

fn set_audio_thread_priority() -> anyhow::Result<()> {
    // https://chromium.googlesource.com/chromium/+/master/base/threading/platform_thread_mac.mm#93

    // 安全：始终可以安全调用
    let thread_id = unsafe { libc::pthread_self() };

    // 安全：thread_id 是有效的线程 id
    let thread_id = unsafe { libc::pthread_mach_thread_np(thread_id) };

    // 固定优先级线程
    let mut policy = thread_extended_policy_data_t { timeshare: 0 };

    // 安全：thread_id 是有效的线程 id
    // 安全：thread_extended_policy_data_t 作为 THREAD_EXTENDED_POLICY 传递
    let result = unsafe {
        mach2::thread_policy::thread_policy_set(
            thread_id,
            THREAD_EXTENDED_POLICY,
            &mut policy as *mut _ as *mut _,
            THREAD_EXTENDED_POLICY_COUNT,
        )
    };

    if result != KERN_SUCCESS {
        anyhow::bail!("failed to set thread extended policy");
    }

    // 相对较高的优先级
    let mut precedence = thread_precedence_policy_data_t { importance: 63 };

    // 安全：thread_id 是有效的线程 id
    // 安全：thread_precedence_policy_data_t 作为 THREAD_PRECEDENCE_POLICY 传递
    let result = unsafe {
        mach2::thread_policy::thread_policy_set(
            thread_id,
            THREAD_PRECEDENCE_POLICY,
            &mut precedence as *mut _ as *mut _,
            THREAD_PRECEDENCE_POLICY_COUNT,
        )
    };

    if result != KERN_SUCCESS {
        anyhow::bail!("failed to set thread precedence policy");
    }

    const GUARANTEED_AUDIO_DUTY_CYCLE: f32 = 0.75;
    const MAX_AUDIO_DUTY_CYCLE: f32 = 0.85;

    // 约 128 帧 @ 44.1KHz
    const TIME_QUANTUM: f32 = 2.9;

    const AUDIO_TIME_NEEDED: f32 = GUARANTEED_AUDIO_DUTY_CYCLE * TIME_QUANTUM;
    const MAX_TIME_ALLOWED: f32 = MAX_AUDIO_DUTY_CYCLE * TIME_QUANTUM;

    let mut timebase_info = mach_timebase_info_data_t { numer: 0, denom: 0 };
    // 安全：timebase_info 是有效的 mach_timebase_info_data_t 结构体指针
    unsafe { mach2::mach_time::mach_timebase_info(&mut timebase_info) };

    let ms_to_abs_time = ((timebase_info.denom as f32) / (timebase_info.numer as f32)) * 1000000f32;

    let mut time_constraints = thread_time_constraint_policy_data_t {
        period: (TIME_QUANTUM * ms_to_abs_time) as u32,
        computation: (AUDIO_TIME_NEEDED * ms_to_abs_time) as u32,
        constraint: (MAX_TIME_ALLOWED * ms_to_abs_time) as u32,
        preemptible: 0,
    };

    // 安全：thread_id 是有效的线程 id
    // 安全：thread_time_constraint_policy_data_t 作为 THREAD_TIME_CONSTRAINT_POLICY 传递
    let result = unsafe {
        mach2::thread_policy::thread_policy_set(
            thread_id,
            THREAD_TIME_CONSTRAINT_POLICY,
            &mut time_constraints as *mut _ as *mut _,
            THREAD_TIME_CONSTRAINT_POLICY_COUNT,
        )
    };

    if result != KERN_SUCCESS {
        anyhow::bail!("failed to set thread time constraint policy");
    }

    Ok(())
}

extern "C" fn trampoline(context: *mut c_void) {
    let runnable =
        unsafe { Runnable::<RunnableMeta>::from_raw(NonNull::new_unchecked(context as *mut ())) };

    let location = runnable.metadata().location;
    let spawned = runnable.metadata().spawned;
    rgpui::profiler::update_running_task(spawned, location);
    runnable.run();
    rgpui::profiler::save_task_timing();
}
