"""Recreate the pinned XNYS core-session calendar used by this study.

MIT license, Edge Quant. Install into an isolated directory before running:
python -m pip install --target deps -r calendar-requirements.txt

exchange_calendars is a third party maintained exchange-calendar library, not
an official NYSE feed. Exceptional closure anchors are checked against NYSE
owner ICE notices. Future sessions through2030 follow known rules as of this
study; future unscheduled closures cannot be known in advance.
"""
from __future__ import annotations

import csv
import hashlib
import importlib.metadata
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
if (HERE / "deps").is_dir():
    sys.path.insert(0, str(HERE / "deps"))

import exchange_calendars as xcals
import pandas as pd

VERSION = "4.13.3"
SOURCES = {
    "library": "https://github.com/gerrymanoim/exchange_calendars",
    "regular_hours_and_holidays": "https://www.nyse.com/markets/hours-calendars",
    "bush_closure": "https://ir.theice.com/press/news-details/2018/New-York-Stock-Exchange-to-Honor-President-George-H-W-Bush/default.aspx",
    "carter_closure": "https://ir.theice.com/press/news-details/2024/The-New-York-Stock-Exchange-Will-Close-Markets-on-January-9-to-Honor-the-Passing-of-Former-President-Jimmy-Carter-on-National-Day-of-Mourning/default.aspx",
}


def main():
    if xcals.__version__ != VERSION:
        raise RuntimeError(f"Expected exchange_calendars=={VERSION}, got{xcals.__version__}")
    cal = xcals.get_calendar("XNYS", start="2015-01-01", end="2030-12-31")
    schedule = cal.schedule
    closed = ["2018-12-05", "2025-01-09", "2016-03-25", "2022-06-20"]
    for day in closed:
        assert pd.Timestamp(day) not in schedule.index, f"Expected closure: {day}"
    expected = {
        "2016-03-11": ("2016-03-11T14:30:00Z", "2016-03-11T21:00:00Z"),
        "2016-03-14": ("2016-03-14T13:30:00Z", "2016-03-14T20:00:00Z"),
        "2016-11-25": ("2016-11-25T14:30:00Z", "2016-11-25T18:00:00Z"),
        "2025-07-03": ("2025-07-03T13:30:00Z", "2025-07-03T17:00:00Z"),
    }
    for day, (open_, close_) in expected.items():
        row = schedule.loc[day]
        assert row["open"] == pd.Timestamp(open_), (day, "open", row["open"])
        assert row["close"] == pd.Timestamp(close_), (day, "close", row["close"])
    assert schedule.index.is_unique and schedule.index.is_monotonic_increasing
    assert (schedule["open"] < schedule["close"]).all()
    path = HERE / "sessions.csv"
    with path.open("w", newline="", encoding="utf-8") as stream:
        writer = csv.writer(stream, lineterminator="\n")
        writer.writerow(["date", "open_utc", "close_utc", "is_early_close", "open_unix", "close_unix"])
        early = 0
        for day, row in schedule.iterrows():
            op, cl = row["open"], row["close"]
            is_early = cl.tz_convert("America/New_York").hour < 16
            early += is_early
            writer.writerow([day.strftime("%Y-%m-%d"), op.strftime("%Y-%m-%dT%H:%M:%SZ"),
                             cl.strftime("%Y-%m-%dT%H:%M:%SZ"), int(is_early),
                             int(op.timestamp()), int(cl.timestamp())])
    source_file = Path(xcals.__file__).parent / "exchange_calendar_xnys.py"
    result = {
        "calendar": "XNYS", "package": "exchange_calendars", "package_version": VERSION,
        "source_file_sha256": hashlib.sha256(source_file.read_bytes()).hexdigest(),
        "session_csv_sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
        "first_session": str(schedule.index[0].date()), "last_session": str(schedule.index[-1].date()),
        "total_sessions": len(schedule), "early_close_sessions": int(early),
        "sessions_by_year": {str(y): int(n) for y, n in pd.Series(schedule.index.year).value_counts().sort_index().items()},
        "utc_timestamps": True, "ny_timezone": "America/New_York",
        "closed_anchor_assertions": closed,
        "open_close_anchor_assertions": expected,
        "sources": SOURCES,
        "limitation": "Third party library using known NYSE rules; future unannounced exceptional closures require calendar regeneration.",
        "runtime_versions": {x: importlib.metadata.version(x) for x in ["pandas", "numpy", "tzdata", "pyluach", "toolz", "korean_lunar_calendar"]},
    }
    (HERE / "sessions.manifest.json").write_text(json.dumps(result, indent=2) + "\n")
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()
