"""Writes RgVectors.mqh, the reference values of TestTradeWindows.mq5.

usage: python make_vectors.py [output file]     default: RgVectors.mqh in the current folder
Place the result in MQL5/Include/RolloverGate, where TestTradeWindows.mq5 includes it.

Every window interval comes from the IANA time zone database through Python's zoneinfo (package tzdata on Windows).
The MQL5 code under test does not use that database. It has its own daylight saving rules, so a match is a consistency
check of those rules against the database for the zones, windows, and years listed here.

The server clock is modelled as Europe/Athens (UTC+2, EU rule), the zone that the clock fit of the Trading Day article
found on MetaQuotes-Demo. A window start or end that falls in the skipped or repeated hour of the server clock is left
out, because a server reading alone cannot name that instant. The number of such cases is printed.
"""
import datetime as dt
import io
import sys
import zoneinfo

UTC = dt.timezone.utc
NY = zoneinfo.ZoneInfo("America/New_York")
SRV = zoneinfo.ZoneInfo("Europe/Athens")
FIRST = dt.date(2025, 1, 1)
LAST = dt.date(2026, 12, 31)
SUN_FRI = 63          # bit d is the weekday on which the window starts, Sunday is bit 0
ALL_DAYS = 127

# name, zone, hour, minute, length in minutes, day mask. "SRV" means the server clock zone.
# NY_ROLLOVER and SRV_ACROSS_MIDNIGHT are the two learned windows of the article's windows files.
SPECS = [
    ("NY_ROLLOVER", NY, 16, 28, 97, SUN_FRI),
    ("NY_ACROSS_MIDNIGHT", NY, 23, 50, 20, SUN_FRI),
    ("SRV_ACROSS_MIDNIGHT", SRV, 23, 28, 97, SUN_FRI),
    ("NY_REPEATED_HOUR", NY, 1, 30, 60, ALL_DAYS),
    ("NY_SKIPPED_HOUR", NY, 2, 30, 60, ALL_DAYS),
]


def to_server(utc_naive):
    """Server wall clock reading of a naive UTC instant, and whether that reading is unique."""
    aware = utc_naive.replace(tzinfo=UTC)
    local = aware.astimezone(SRV)
    naive = local.replace(tzinfo=None)
    first = naive.replace(tzinfo=SRV, fold=0).astimezone(UTC)
    second = naive.replace(tzinfo=SRV, fold=1).astimezone(UTC)
    unique = first == second and first == aware
    return naive, unique


def intervals(zone, hour, minute, length, mask):
    """Server clock start and end of every window, one per local date that the mask allows."""
    out = []
    skipped = 0
    d = FIRST
    while d <= LAST:
        weekday = (d.weekday() + 1) % 7            # Python Monday is 0, MQL5 Sunday is 0
        if mask & (1 << weekday):
            local = dt.datetime(d.year, d.month, d.day, hour, minute, tzinfo=zone, fold=0)
            start_utc = local.astimezone(UTC).replace(tzinfo=None)
            end_utc = start_utc + dt.timedelta(minutes=length)
            s, ok1 = to_server(start_utc)
            e, ok2 = to_server(end_utc)
            if ok1 and ok2:
                out.append((s, e))
            else:
                skipped += 1
        d += dt.timedelta(days=1)
    return out, skipped


def lit(naive):
    return "D'%s'" % naive.strftime("%Y.%m.%d %H:%M:%S")


def array(name, items):
    lines = []
    for i in range(0, len(items), 3):
        lines.append("   " + ",".join(items[i:i + 3]))
    return "const datetime %s[]=\n  {\n%s\n  };\n" % (name, ",\n".join(lines))


def main():
    path = sys.argv[1] if len(sys.argv) > 1 else "RgVectors.mqh"
    out = []
    out.append("//+------------------------------------------------------------------+")
    out.append("//|                                                    RgVectors.mqh |")
    out.append("//|                                       Copyright 2026, Ali Rajput |")
    out.append("//+------------------------------------------------------------------+")
    out.append("#property copyright \"Copyright 2026, Ali Rajput\"")
    out.append("//--- Generated by make_vectors.py from the IANA time zone database (Python zoneinfo).")
    out.append("//--- Server clock: Europe/Athens. Each list holds start, end, start, end, ... as server clock readings.")
    out.append("")
    for name, zone, h, m, length, mask in SPECS:
        z = SRV if zone is SRV else zone
        iv, skipped = intervals(z, h, m, length, mask)
        flat = []
        for s, e in iv:
            flat.append(lit(s))
            flat.append(lit(e))
        out.append("//+------------------------------------------------------------------+")
        out.append("//| %-64s |" % ("%s: %02d:%02d for %d minutes, %d windows" % (name, h, m, length, len(iv))))
        out.append("//+------------------------------------------------------------------+")
        out.append(array("V_%s" % name, flat))
        print(name, "windows", len(iv), "left out", skipped)
        if name == "NY_ROLLOVER":
            other = sum(1 for start, end in iv if start.strftime("%H:%M") != "23:28")
    print("NY_ROLLOVER windows with a server start other than 23:28:", other)
    io.open(path, "w", encoding="utf-8", newline="\n").write("\n".join(out))


main()
