"""Reproduce: FINOS Common Domain Model YearFraction for 30E/360 (ISDA).

    pip install finos-cdm==7.12.0          # optional: pip install QuantLib
    python cdm-30e360-isda-check.py

Runs the official generated Python code of the CDM and compares it with the
30E/360 (ISDA) formula of the 2006 ISDA Definitions, Section 4.16(h).
GERO Research, 5 December 2026.
"""
import datetime as dt
import importlib.metadata as md
import random

import finos.cdm.base.datetime.daycount.functions.YearFraction as cdm
from finos.cdm.base.datetime.daycount.DayCountFractionEnum import DayCountFractionEnum as E

print("finos-cdm", md.version("finos-cdm"))
try:
    cdm.YearFraction(E._30E_360_ISDA, dt.date(2024, 1, 15), dt.date(2024, 2, 20), dt.date(2030, 1, 15), 2)
except NameError as error:
    print("As shipped:", error)
# The package does not define the Rune built-in IsLeapYear; supply it so that the
# generated 30E/360 (ISDA) logic itself runs unchanged.
cdm.finos_com_rosetta_model_IsLeapYear = lambda y: y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)


def last_day_of_february(d):
    return d.month == 2 and (d + dt.timedelta(days=1)).month == 3


def isda_30e360(start, end, termination):
    """2006 ISDA Definitions 4.16(h)."""
    d1 = 30 if last_day_of_february(start) or start.day == 31 else start.day
    d2 = 30 if (last_day_of_february(end) and end != termination) or end.day == 31 else end.day
    return (360 * (end.year - start.year) + 30 * (end.month - start.month) + (d2 - d1)) / 360


def cdm_30e360(start, end, termination):
    return float(cdm.YearFraction(E._30E_360_ISDA, start, end, termination, 2))


D = dt.date
print(f"\n{'start':10s}  {'end':10s}  {'termination':11s}  {'CDM':>5s}  {'ISDA':>5s}   (days on a 360 basis)")
for start, end, termination in [(D(2024, 1, 15), D(2024, 2, 20), D(2030, 1, 15)),
                                (D(2024, 3, 15), D(2024, 9, 15), D(2024, 9, 15)),
                                (D(2025, 8, 31), D(2026, 2, 28), D(2026, 2, 28)),
                                (D(2024, 3, 15), D(2024, 9, 15), D(2030, 3, 15))]:
    print(f"{start}  {end}  {termination}   {cdm_30e360(start, end, termination) * 360:5.0f}  "
          f"{isda_30e360(start, end, termination) * 360:5.0f}")

random.seed(1)
base, differ, n = D(2020, 1, 1), 0, 3000
cases = []
for _ in range(n):
    s = base + dt.timedelta(random.randint(0, 3000))
    e = s + dt.timedelta(random.randint(28, 200))
    t = e + dt.timedelta(random.randint(1, 3000))
    cases.append((s, e, t))
    differ += abs(cdm_30e360(s, e, t) - isda_30e360(s, e, t)) > 1e-12
print(f"\nRandom periods (seed 1): CDM differs from the ISDA formula in {differ} of {n}")

try:
    import QuantLib as ql
    q = lambda x: ql.Date(x.day, x.month, x.year)
    mism = sum(abs(ql.Thirty360(ql.Thirty360.German, q(t)).yearFraction(q(s), q(e)) - isda_30e360(s, e, t)) > 1e-12
               for s, e, t in cases)
    print(f"QuantLib {ql.__version__} Thirty360(German) vs the ISDA formula: {mism} differences")
except ImportError:
    print("QuantLib not installed; skipping the cross-check")

notional, rate = 100_000_000, 0.04
wrong = notional * rate * cdm_30e360(D(2024, 3, 15), D(2024, 9, 15), D(2024, 9, 15))
right = notional * rate * isda_30e360(D(2024, 3, 15), D(2024, 9, 15), D(2024, 9, 15))
print(f"\nFinal coupon, 100m at 4%, 15 Mar - 15 Sep, termination 15 Sep: CDM {wrong:,.0f}, ISDA {right:,.0f}, "
      f"difference {wrong - right:,.0f}")
