#!/usr/bin/env python3
"""p011 orrery -- the Moon's gear train, pure arithmetic.  Brim (an AI agent), wake 329.

Layout this computes for (DESIGN.md, Decided 2):
  a carrier wheel turns once a year about a fixed centre post.
  N1 is FIXED to the post.  On the carrier: an idler (any size) meshes N1;
  N2 meshes the idler; N3 is one part with N2; N4 at the Earth pin meshes N3
  and carries the Moon.
  Seen from the carrier, N4 turns  +(N1/N2)*(N3/N4)  times per year, the same
  way the carrier goes round.  The Sun is always along the carrier's radius,
  so that number is the count of SYNODIC months (new moon to new moon) in one
  trip round the Sun.

Target: sidereal year / synodic month = 365.256363 / 29.530589.

usage: train.py [min_driven_teeth] [max_teeth] [how_many]
"""
import sys
from fractions import Fraction

YEAR = 365.256363      # sidereal year, days (one full trip round the Sun against the stars)
SYNODIC = 29.530589    # mean synodic month, days
TARGET = YEAR / SYNODIC

def search(lo=14, hi=80, keep=12):
    out = []
    for n2 in range(lo, 31):
        for n4 in range(lo, 31):
            if n4 < n2:
                continue            # (n2,n4) and (n4,n2) give the same ratio set
            for n1 in range(30, hi + 1):
                # best n3 for this triple
                x = TARGET * n2 * n4 / n1
                for n3 in (int(x), int(x) + 1):
                    if not (20 <= n3 <= hi):
                        continue
                    r = Fraction(n1 * n3, n2 * n4)
                    out.append((abs(float(r) - TARGET), n1, n2, n3, n4, r))
    out.sort()
    seen, res = set(), []
    for e, n1, n2, n3, n4, r in out:
        if r in seen:
            continue
        seen.add(r)
        res.append((e, n1, n2, n3, n4, r))
        if len(res) >= keep:
            break
    return res

def report(n1, n2, n3, n4):
    r = Fraction(n1 * n3, n2 * n4)
    ratio = float(r)
    err = ratio - TARGET                     # synodic months per year, too many (+) or too few (-)
    deg_per_year = err * 360.0               # Moon's phase angle gained per cranked year
    month_model = YEAR / ratio               # the machine's synodic month, in days of its own year
    years_to_one_day = (360.0 / SYNODIC) / abs(deg_per_year) if err else float("inf")
    return dict(r=r, ratio=ratio, err=err, deg_per_year=deg_per_year,
                month_model=month_model, years_to_one_day=years_to_one_day)

if __name__ == "__main__":
    a = [int(x) for x in sys.argv[1:]]
    lo = a[0] if len(a) > 0 else 14
    hi = a[1] if len(a) > 1 else 80
    keep = a[2] if len(a) > 2 else 12
    print(f"target {TARGET:.6f} synodic months per sidereal year")
    print("  N1(fixed) N2  N3  N4   ratio        error     deg/yr   model month   years until 1 day of phase off")
    for e, n1, n2, n3, n4, r in search(lo, hi, keep):
        d = report(n1, n2, n3, n4)
        print(f"  {n1:3d}      {n2:3d} {n3:3d} {n4:3d}   {d['ratio']:.6f}  {d['err']:+.6f}  {d['deg_per_year']:+7.3f}  {d['month_model']:.4f} d    {d['years_to_one_day']:.0f}")
