#pragma once
#include <windows.h>
#include <string>
#include <cwctype>

struct UsageStats {
    double totalAudioSec  = 0;
    double totalProcSec   = 0;
    double totalWords     = 0;
    double totalClips     = 0;
    double longestClipSec = 0;
};

inline std::wstring StatsIniPath() {
    wchar_t buf[MAX_PATH]; GetModuleFileNameW(nullptr, buf, MAX_PATH);
    std::wstring p(buf); p = p.substr(0, p.find_last_of(L"\\/"));
    return p + L"\\win-dictation.ini";
}
inline void   StPut(const wchar_t* k, double v) {
    wchar_t b[64]; swprintf_s(b, L"%.3f", v);
    WritePrivateProfileStringW(L"stats", k, b, StatsIniPath().c_str());
}
inline double StGet(const wchar_t* k) {
    wchar_t out[64];
    GetPrivateProfileStringW(L"stats", k, L"0", out, 64, StatsIniPath().c_str());
    return wcstod(out, nullptr);
}
inline void LoadStats(UsageStats& s) {
    s.totalAudioSec = StGet(L"audioSec");  s.totalProcSec   = StGet(L"procSec");
    s.totalWords    = StGet(L"words");     s.totalClips     = StGet(L"clips");
    s.longestClipSec= StGet(L"longest");
}
inline void SaveStats(const UsageStats& s) {
    StPut(L"audioSec", s.totalAudioSec);   StPut(L"procSec", s.totalProcSec);
    StPut(L"words", s.totalWords);         StPut(L"clips", s.totalClips);
    StPut(L"longest", s.longestClipSec);
}

inline int CountWords(const std::wstring& s) {
    int n = 0; bool in = false;
    for (wchar_t c : s) { bool w = !iswspace(c); if (w && !in) ++n; in = w; }
    return n;
}
inline void RecordUsage(UsageStats& st, double audioSec, double procSec, const std::wstring& text) {
    st.totalAudioSec += audioSec;
    st.totalProcSec  += procSec;
    st.totalWords    += CountWords(text);
    st.totalClips    += 1;
    if (audioSec > st.longestClipSec) st.longestClipSec = audioSec;
    SaveStats(st);
}

inline std::wstring FormatHMS(double sec) {
    int s = (int)(sec + 0.5), h = s / 3600, m = (s % 3600) / 60; s %= 60;
    wchar_t b[64];
    if (h)      swprintf_s(b, L"%dh %dm", h, m);
    else if (m) swprintf_s(b, L"%dm %ds", m, s);
    else        swprintf_s(b, L"%ds", s);
    return b;
}
