// DisplayHost 实现 — LVGL 初始化(fbdev + evdev)与调度
#include "display/display_host.h"

#include "common/log.h"
#include "common/time_utils.h"

#include "lvgl.h"

#include <cstdio>
#include <cstring>
#include <unistd.h>

namespace hwdisplay {
namespace {

int         s_width   = 0;
int         s_height  = 0;
uint32_t    s_idle    = 0;   // 空闲率(%), 由应用主循环更新

uint32_t TickCb(void) { return (uint32_t)(hwtime::now_us() / 1000ULL); }

}  // namespace

// LVGL sysmon 的 CPU 占用计算入口(见 third_party/lv_conf.h: LV_SYSMON_GET_IDLE)
extern "C" uint32_t hw_idle_percent(void) { return s_idle; }

void SetIdlePercent(uint32_t percent) { s_idle = percent > 100 ? 100 : percent; }

bool Init(const char* fb_path, const char* input_path) {
    setvbuf(stdout, nullptr, _IOLBF, 0);   // 行缓冲: nohup 重定向也能及时看日志

    lv_init();
    lv_tick_set_cb(TickCb);

    lv_display_t* disp = lv_linux_fbdev_create();
    if (!disp) {
        HW_ERR("display: 创建 fbdev 显示失败 (%s)", fb_path);
        return false;
    }
    lv_linux_fbdev_set_file(disp, fb_path);
    s_width  = (int)lv_display_get_horizontal_resolution(disp);
    s_height = (int)lv_display_get_vertical_resolution(disp);
    HW_LOG("display: %s %dx%d (LV_COLOR_DEPTH=%d)", fb_path, s_width, s_height,
           (int)LV_COLOR_DEPTH);

    lv_indev_t* indev = lv_evdev_create(LV_INDEV_TYPE_POINTER, input_path);
    if (!indev) HW_WARN("display: 打开输入设备失败 %s(无触摸继续)", input_path);
    else        HW_LOG("display: input %s 触摸就绪", input_path);

    // 屏幕底色(视频窗之外的区域)
    lv_obj_set_style_bg_color(lv_screen_active(), lv_color_black(), 0);
    lv_obj_set_style_bg_opa(lv_screen_active(), LV_OPA_COVER, 0);
    return true;
}

uint32_t Tick() {
    uint32_t delay = lv_timer_handler();
    if (delay < 3) delay = 3;
    return delay;
}

int Width() { return s_width; }
int Height() { return s_height; }

void LayoutTwoPanes(const std::string& mode, int sw, int sh, int top_offset, int status_h,
                    int* main_rc, int* sub_rc) {
    (void)sh;
    if (mode == "v") {   // 上下两格
        const int pw = 384, ph = 216;
        const int x  = (sw - pw) / 2;
        main_rc[0] = x; main_rc[1] = top_offset;            main_rc[2] = pw; main_rc[3] = ph;
        sub_rc[0]  = x; sub_rc[1]  = top_offset + ph + 4;   sub_rc[2]  = pw; sub_rc[3]  = ph;
    } else if (mode == "pip") {   // 主画面(800x450) + 右下画中画
        const int pw = sw, ph = sw * 9 / 16;
        const int sw2 = 240, sh2 = 135;
        main_rc[0] = 0;            main_rc[1] = top_offset;          main_rc[2] = pw;  main_rc[3] = ph;
        sub_rc[0]  = sw - sw2 - 8; sub_rc[1]  = top_offset + ph - sh2 - 8;
        sub_rc[2]  = sw2;          sub_rc[3]  = sh2;
    } else {   // "h": 左右两格, 靠顶(底部留出内容区)
        const int pw = sw / 2, ph = pw * 9 / 16;
        (void)status_h;
        main_rc[0] = 0;  main_rc[1] = top_offset; main_rc[2] = pw; main_rc[3] = ph;
        sub_rc[0]  = pw; sub_rc[1]  = top_offset; sub_rc[2]  = pw; sub_rc[3]  = ph;
    }
}

double PollProcessCpu() {
    static uint64_t last_ticks = 0;
    static uint64_t last_us    = 0;
    static double   percent    = 0;

    FILE* fp = fopen("/proc/self/stat", "r");
    if (!fp) return percent;
    char   buf[512];
    size_t n = fread(buf, 1, sizeof(buf) - 1, fp);
    fclose(fp);
    buf[n] = '\0';
    const char* p = strrchr(buf, ')');
    if (!p) return percent;

    uint64_t ut = 0, st = 0;
    if (sscanf(p + 2, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %llu %llu", &ut,
               &st) != 2)
        return percent;

    uint64_t ticks = ut + st;
    uint64_t now   = hwtime::now_us();
    long     hz    = sysconf(_SC_CLK_TCK);
    if (last_us && now > last_us) {
        double dt_ticks = (double)(ticks - last_ticks) / (double)(hz > 0 ? hz : 100);
        double dt_wall  = (double)(now - last_us) / 1e6;
        if (dt_wall > 0) percent = 100.0 * dt_ticks / dt_wall;
    }
    last_ticks = ticks;
    last_us    = now;

    SetIdlePercent(percent >= 100 ? 0 : (uint32_t)(100.0 - percent));
    return percent;
}

void LogLvMem(const char* tag) {
    lv_mem_monitor_t m{};
    lv_mem_monitor(&m);
    HW_LOG("lvgl 内存[%s]: 总 %uKB, 空闲 %.0fKB, 最大可用块 %.0fKB, 碎片 %u%%", tag,
           m.total_size / 1024, m.free_size / 1024.0, m.free_biggest_size / 1024.0, m.frag_pct);
}

}  // namespace hwdisplay
