*******************************************************************************
*! __wbod_write_stats_history v1.0.0  09Feb2026
*! Write sync statistics to history YAML file
*! Author: João Pedro Azevedo (World Bank | UNICEF)
*! Contact: https://jpazvd.github.io
*! License: MIT
*******************************************************************************

program define __wbod_write_stats_history
    version 14.0
    syntax , ///
        METHOD(string)              /// Sync method used (python, stata, github)
        INDICATORS(integer)         /// Total indicator count
        SOURCES(integer)            /// Total source count
        TOPICS(integer)             /// Total topic count
        [                           ///
        COUNTRIES(integer 0)        /// Country metadata count
        BYSOURCE(string)            /// Source counts as "id1:n1 id2:n2 ..."
        BYTOPIC(string)             /// Topic counts as "id1:n1 id2:n2 ..."
        ]

    *---------------------------------------------------------------------------
    * 1. Resolve history file path
    *---------------------------------------------------------------------------
    local cache_base "`c(sysdir_plus)'_/"
    local cache_base : subinstr local cache_base "\" "/" , all

    * Ensure directory exists
    capture mkdir "`cache_base'"

    local history_file "`cache_base'_wbopendata_cache_stats_history.yaml"

    *---------------------------------------------------------------------------
    * 2. Generate timestamp
    *---------------------------------------------------------------------------
    local datef = c(current_date)
    local timef = c(current_time)
    local timestamp "`datef' `timef'"

    * Also create ISO format timestamp
    local day = word("`datef'", 1)
    local mon = word("`datef'", 2)
    local yr = word("`datef'", 3)

    * Convert month abbreviation to number
    local months "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
    local mon_num = 0
    forvalues i = 1/12 {
        if (word("`months'", `i') == "`mon'") {
            local mon_num = `i'
        }
    }
    if (`mon_num' < 10) local mon_num = "0`mon_num'"
    if (length("`day'") == 1) local day = "0`day'"

    local iso_date = "`yr'-`mon_num'-`day'T`timef'Z"

    *---------------------------------------------------------------------------
    * 3. Check if file exists and read existing entries count
    *---------------------------------------------------------------------------
    local file_exists = 0
    local entry_count = 0

    capture confirm file "`history_file'"
    if (_rc == 0) {
        local file_exists = 1
        * Count existing entries by counting "  - synced_at:" lines
        tempname fh
        file open `fh' using "`history_file'", read text
        file read `fh' line
        while r(eof) == 0 {
            if (strpos("`line'", "  - synced_at:") > 0) {
                local entry_count = `entry_count' + 1
            }
            file read `fh' line
        }
        file close `fh'
    }

    *---------------------------------------------------------------------------
    * 4. Write new entry
    *---------------------------------------------------------------------------
    tempname fh

    if (`file_exists' == 0) {
        * Create new file with header
        file open `fh' using "`history_file'", write text replace
        file write `fh' "# wbopendata sync statistics history" _n
        file write `fh' "# Auto-generated by __wbod_write_stats_history.ado" _n
        file write `fh' "# Format: YAML list of sync events" _n
        file write `fh' "" _n
        file write `fh' "_metadata:" _n
        file write `fh' "  version: 1.0.0" _n
        file write `fh' "  description: Historical record of metadata sync operations" _n
        file write `fh' "  created_at: '`iso_date''" _n
        file write `fh' "" _n
        file write `fh' "history:" _n
    }
    else {
        * Append to existing file
        file open `fh' using "`history_file'", write text append
    }

    * Write the new entry
    file write `fh' "  - synced_at: '`iso_date''" _n
    file write `fh' "    method: `method'" _n
    file write `fh' "    indicators: `indicators'" _n
    file write `fh' "    sources: `sources'" _n
    file write `fh' "    topics: `topics'" _n

    * Add countries if provided
    if (`countries' > 0) {
        file write `fh' "    countries: `countries'" _n
    }

    * Add by_source breakdown if provided
    if ("`bysource'" != "") {
        file write `fh' "    by_source:" _n
        local srclist "`bysource'"
        while ("`srclist'" != "") {
            gettoken pair srclist : srclist
            local sid = word(subinstr("`pair'", ":", " ", 1), 1)
            local cnt = word(subinstr("`pair'", ":", " ", 1), 2)
            file write `fh' "      '`sid'': `cnt'" _n
        }
    }

    * Add by_topic breakdown if provided
    if ("`bytopic'" != "") {
        file write `fh' "    by_topic:" _n
        local toplist "`bytopic'"
        while ("`toplist'" != "") {
            gettoken pair toplist : toplist
            local tid = word(subinstr("`pair'", ":", " ", 1), 1)
            local cnt = word(subinstr("`pair'", ":", " ", 1), 2)
            file write `fh' "      '`tid'': `cnt'" _n
        }
    }

    file close `fh'

    *---------------------------------------------------------------------------
    * 5. Display confirmation
    *---------------------------------------------------------------------------
    local new_count = `entry_count' + 1
    di as text "Stats history updated: " as result "`new_count' entries"
    di as text "  File: " as result "`history_file'"

    *---------------------------------------------------------------------------
    * 6. Return values
    *---------------------------------------------------------------------------
    return local history_file "`history_file'"
    return scalar entry_count = `new_count'
end