from fractions import Fraction
from math import factorial, log10
from komorebi_math.sequences import reciprocal_coefficients
from komorebi_browser import show_plot, export_file

# D_N(t)^(-r) = sum A(n) t^(N*n) / (N*n)!
# Change these integer parameters and run again.
N, r, count = 4, 1, 16
if not (type(N) is int and 2 <= N <= 8 and type(r) is int and 1 <= r <= 3
        and type(count) is int and 2 <= count <= 16):
    raise ValueError("Use N=2..8, r=1..3, and count=2..16 for this experiment.")
a = reciprocal_coefficients(N, count, power=r)
ns = list(range(count))
scale = [factorial(N*n) for n in ns]
normalized = [Fraction(a[n], scale[n]) for n in ns]
if any(value <= 0 for value in a):
    raise ValueError("This logarithmic view requires positive coefficients.")

show_plot([
    {"x": ns, "y": [log10(value) for value in a], "mode": "lines+markers",
     "name": "Sequence A(n)", "line": {"color": "#0067a5"}, "marker": {"symbol": "circle"},
     "hovertemplate": "n = %{x}<br>log10 A(n) = %{y:.3f}<extra>Sequence</extra>"},
    {"x": ns, "y": [log10(value) for value in scale], "mode": "lines+markers",
     "name": "Factorial (Nn)!", "line": {"color": "#b54b00", "dash": "dash"}, "marker": {"symbol": "diamond"},
     "hovertemplate": "n = %{x}<br>log10 (Nn)! = %{y:.3f}<extra>Factorial</extra>"}],
    {"title": {"text": f"Sequence and factorial growth (N={N}, r={r})"},
     "xaxis": {"title": {"text": "Index n"}, "dtick": 2},
     "yaxis": {"title": {"text": "Size, in powers of 10"}}},
    description="Blue circles show A(n). Orange diamonds show (Nn)!. A height of 20 means 10 to the power 20. Each step in n adds N to the degree. This finite comparison does not establish an asymptotic equivalence.")
show_plot([{"x": ns,
    "y": [log10(v.numerator)-log10(v.denominator) for v in normalized],
    "mode": "lines+markers", "name": "Normalized coefficients",
    "hovertemplate": "n = %{x}<br>log10 normalized value = %{y:.3f}<extra></extra>"}],
    {"title": {"text": f"After division by (Nn)!: N={N}, r={r}"},
     "xaxis": {"title": {"text": "Index n"}, "dtick": 2},
     "yaxis": {"title": {"text": "Normalized size (log10)"}}},
    description="Each value is A(n) divided by (Nn)!. A height of -3 means 0.001. A fall of one unit means a value ten times smaller. Lines connect discrete samples. Exact fractions are in the CSV below.")
csv = "N,r,n,degree,A,factorial,normalized_fraction\n"
csv += "".join(f"{N},{r},{n},{N*n},{a[n]},{scale[n]},{normalized[n]}\n" for n in ns)
export_file("reciprocal-growth-exact.csv", csv)
print(f"Reciprocal family: N={N}, r={r}")
print(f"Computed n=0 through {count-1} with exact integers.")
print("A(0..4):", a[:5])
print("Exported exact coefficients and rational normalizations.")
