"""Writes TdVectors.mqh, the reference values of TestTradingDay.mq5.

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

Every value 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. The MQL5 code has its own rules, so a match is a consistency
check of those rules against the database values, for the zones and years listed here.

The server clock is modelled as Europe/Athens (UTC+2, EU rule), the zone that the fit tool found on MetaQuotes-Demo.
"""
import datetime as dt
import io
import sys
import zoneinfo

UTC = dt.timezone.utc
NY = zoneinfo.ZoneInfo("America/New_York")
CE = zoneinfo.ZoneInfo("Europe/Prague")
SRV = zoneinfo.ZoneInfo("Europe/Athens")
EPOCH = dt.datetime(1970, 1, 1)


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


def to_naive_utc(aware):
    return aware.astimezone(UTC).replace(tzinfo=None)


def transitions(tz, year):
    """UTC instants at which the zone changes its offset in a year (first instant with the new offset)."""
    out = []
    t = dt.datetime(year, 1, 1, tzinfo=UTC)
    prev = t.astimezone(tz).utcoffset()
    while t.year == year:
        t += dt.timedelta(minutes=30)
        off = t.astimezone(tz).utcoffset()
        if off != prev:
            out.append(t.replace(tzinfo=None))
            prev = off
    return out


def boundaries(tz, hour, minute, fold, first, last):
    """Server wall-clock timestamps of the day starts of a definition, one per calendar day from first to last."""
    out = []
    d = first
    while d <= last:
        local = dt.datetime(d.year, d.month, d.day, hour, minute, tzinfo=tz, fold=fold)
        utc = local.astimezone(UTC)
        out.append(utc.astimezone(SRV).replace(tzinfo=None))
        d += dt.timedelta(days=1)
    return out


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


WINDOWS = [(dt.date(2025, 3, 3), dt.date(2025, 4, 7)), (dt.date(2025, 10, 20), dt.date(2025, 11, 10)),
           (dt.date(2026, 3, 2), dt.date(2026, 4, 6)), (dt.date(2026, 10, 19), dt.date(2026, 11, 9))]
EDGE = [(dt.date(2025, 3, 6), dt.date(2025, 3, 12)), (dt.date(2025, 10, 30), dt.date(2025, 11, 5)),
        (dt.date(2026, 3, 5), dt.date(2026, 3, 11)), (dt.date(2026, 10, 29), dt.date(2026, 11, 4))]
EDGE_EU = [(dt.date(2025, 3, 27), dt.date(2025, 4, 2)), (dt.date(2025, 10, 23), dt.date(2025, 10, 29)),
           (dt.date(2026, 3, 26), dt.date(2026, 4, 1)), (dt.date(2026, 10, 22), dt.date(2026, 10, 28))]


def windowed(tz, hour, minute, fold, windows):
    items = []
    for first, last in windows:
        items += boundaries(tz, hour, minute, fold, first, last)
        items.append(None)
    return items


def dt_or_break(x):
    return "0" if x is None else lit(x)


def main():
    out = []
    out.append("""//+------------------------------------------------------------------+
//|                                                    TdVectors.mqh |
//|                                       Copyright 2026, Ali Rajput |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Ali Rajput"
//--- Generated by tools/make_vectors.py from the IANA time zone database (Python zoneinfo).
//--- Server clock: Europe/Athens. A 0 in a boundary list ends a window of consecutive days.
""")
    ny_tr, ce_tr = [], []
    for y in range(2015, 2036):
        ny_tr += transitions(NY, y)
        ce_tr += transitions(CE, y)
    out.append("//+------------------------------------------------------------------+\n"
               "//| Daylight saving changes in UTC, 2015 to 2035, start then end     |\n"
               "//+------------------------------------------------------------------+\n")
    out.append(array("datetime", "V_NY_CHANGES", ny_tr, lit))
    out.append(array("datetime", "V_CE_CHANGES", ce_tr, lit))
    # offsets one second before and at each change in 2024 to 2026
    for name, tz, trs in (("NY", NY, ny_tr), ("CE", CE, ce_tr)):
        utcs, offs = [], []
        for t in trs:
            if 2024 <= t.year <= 2026:
                for d in (-1, 0):
                    x = t + dt.timedelta(seconds=d)
                    utcs.append(x)
                    offs.append(int(x.replace(tzinfo=UTC).astimezone(tz).utcoffset().total_seconds()))
        out.append("//+------------------------------------------------------------------+\n"
                   "//| Offset from UTC in seconds, %s, around each change in 2024-2026  |\n"
                   "//+------------------------------------------------------------------+\n" % name)
        out.append(array("datetime", "V_%s_OFF_UTC" % name, utcs, lit))
        out.append(array("int", "V_%s_OFF_VALUE" % name, offs, str, 8))
    # local to UTC cases
    cases = [(0, dt.datetime(2026, 3, 8, 1, 59, 59)), (0, dt.datetime(2026, 3, 8, 2, 0, 0)), (0, dt.datetime(2026, 3, 8, 2, 30, 0)),
             (0, dt.datetime(2026, 3, 8, 3, 0, 0)), (0, dt.datetime(2026, 11, 1, 0, 59, 59)), (0, dt.datetime(2026, 11, 1, 1, 0, 0)),
             (0, dt.datetime(2026, 11, 1, 1, 30, 0)), (0, dt.datetime(2026, 11, 1, 2, 0, 0)), (1, dt.datetime(2026, 3, 29, 1, 59, 59)),
             (1, dt.datetime(2026, 3, 29, 2, 0, 0)), (1, dt.datetime(2026, 3, 29, 2, 30, 0)), (1, dt.datetime(2026, 3, 29, 3, 0, 0)),
             (1, dt.datetime(2026, 10, 25, 2, 0, 0)), (1, dt.datetime(2026, 10, 25, 2, 30, 0)), (1, dt.datetime(2026, 10, 25, 3, 0, 0)),
             (0, dt.datetime(2025, 3, 9, 2, 30, 0)), (0, dt.datetime(2025, 11, 2, 1, 30, 0)), (1, dt.datetime(2025, 3, 30, 2, 30, 0)),
             (1, dt.datetime(2025, 10, 26, 2, 30, 0)), (0, dt.datetime(2026, 7, 1, 12, 0, 0)), (1, dt.datetime(2026, 1, 15, 12, 0, 0))]
    zid, loc, fold, utc, kind = [], [], [], [], []
    for z, local in cases:
        tz = NY if z == 0 else CE
        a0 = dt.datetime(local.year, local.month, local.day, local.hour, local.minute, local.second, tzinfo=tz, fold=0)
        a1 = a0.replace(fold=1)
        u0 = to_naive_utc(a0)
        u1 = to_naive_utc(a1)
        # a reading is skipped when converting back does not give it again
        back = u0.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
        is_gap = back != local
        is_fold = (not is_gap) and u0 != u1
        for f, u in ((0, u0), (1, u1)):
            if is_gap and f == 1:
                continue                      # the library moves a skipped reading forward in the same way for both folds
            zid.append(z)
            loc.append(local)
            fold.append(f)
            utc.append(u)
            kind.append(1 if is_gap else (2 if is_fold else 0))
    out.append("//+------------------------------------------------------------------+\n"
               "//| Local reading to UTC: zone (0 New York, 1 Central Europe), the   |\n"
               "//| reading, fold (0 first, 1 second), UTC result, kind (0 once,     |\n"
               "//| 1 skipped, 2 twice)                                              |\n"
               "//+------------------------------------------------------------------+\n")
    out.append(array("int", "V_L2U_ZONE", zid, str, 12))
    out.append(array("datetime", "V_L2U_LOCAL", loc, lit))
    out.append(array("int", "V_L2U_FOLD", fold, str, 12))
    out.append(array("datetime", "V_L2U_UTC", utc, lit))
    out.append(array("int", "V_L2U_KIND", kind, str, 12))
    # day starts of the presets
    defs = [("SERVER", SRV, 0, 0, 0, WINDOWS), ("NYCLOSE", NY, 17, 0, 0, WINDOWS), ("CEMID", CE, 0, 0, 0, WINDOWS),
            ("NY0230_FIRST", NY, 2, 30, 0, EDGE), ("NY0130_FIRST", NY, 1, 30, 0, EDGE), ("NY0130_SECOND", NY, 1, 30, 1, EDGE),
            ("CE0230_FIRST", CE, 2, 30, 0, EDGE_EU)]
    out.append("//+------------------------------------------------------------------+\n"
               "//| Day starts in server time, consecutive days, windows end with 0  |\n"
               "//+------------------------------------------------------------------+\n")
    for name, tz, h, m, f, win in defs:
        out.append(array("datetime", "V_DAY_" + name, windowed(tz, h, m, f, win), dt_or_break))
    text = "\n".join(out)
    path = sys.argv[1] if len(sys.argv) > 1 else "TdVectors.mqh"
    io.open(path, "w", encoding="utf-8", newline="\n").write(text)
    print("wrote", path, len(text), "chars")


main()
