#include <stdint.h>
#include "arch/x86_64/pit.h"
#include "arch/x86_64/io.h"
#include "stdio.h"
#include "time.h"

extern uint64_t PIT_GetTicks(void);

volatile uint64_t tsc_cycles_per_us = 0;

uint64_t rdtsc(void)
{
    uint32_t lo, hi;
    __asm__ volatile ("rdtsc" : "=a"(lo), "=d"(hi));
    return ((uint64_t)hi << 32) | lo;
}


void calibrate_tsc(void)
{
    // Use a stable PIT rate for calibration
    const uint32_t pit_freq = 1000; // 100 Hz = 10ms per tick
    const uint32_t calibration_ticks = 1000; // 1 second total



    // Wait for PIT to stabilize
    uint64_t start_ticks = PIT_GetTicks();
    while (PIT_GetTicks() == start_ticks)
        ;

    uint64_t start_tsc = rdtsc();
    uint64_t target_ticks = start_ticks + calibration_ticks;

    // Wait for known number of PIT ticks
    while (PIT_GetTicks() < target_ticks)
        ;

    uint64_t end_tsc = rdtsc();

    // Compute elapsed time
    uint64_t tsc_delta = end_tsc - start_tsc;

    // 100 ticks at 100 Hz = 1 second = 1,000,000 microseconds
    uint64_t elapsed_us = 1000000ULL;

    tsc_cycles_per_us = tsc_delta / elapsed_us;

    printf("TSC calibration complete: %lu cycles/us\n", tsc_cycles_per_us);
}