"""Extract a tiny fixed parameter calculation after the reader fetches the source.

No author observation table or light curve is vendored/reissued. The source's
Table 1 is used, including its fitted (not abstract-rounded) component masses.
The 19 s/year is the paper's adopted observed trend, not an independent fit.
"""
from html import unescape
import hashlib
import re

from roche_reference import eggleton


def beta_lyrae_conditional(source_path):
    if hashlib.sha256(source_path.read_bytes()).hexdigest() != "7c218201125132c16ea8265ac1469728561f54d40fad047d57787dd3638741bf":
        raise ValueError("Fixed historical full-text input changed; source review is required")
    source = unescape(source_path.read_text())
    def fitted_mass(component):
        pattern = r"\\cal M_\{\\rm\{\}_\{"+component+r"\}\}\{\[\\cal M_\{\\odot\}\]\}&([0-9.]+)\\pm ([0-9.]+)"
        match = re.search(pattern, source)
        if not match:
            raise ValueError("Fixed source's Table 1 mass field did not match")
        return tuple(map(float, match.groups()))
    accretor, accretor_error = fitted_mass("h")
    donor, donor_error = fitted_mass("c")
    period_match = re.search(r"orbital period of ([0-9.]+) days increasing at a rate of ([0-9.]+) s yr", source)
    if not period_match:
        raise ValueError("Fixed source's adopted period trend did not match")
    period_days, period_trend_seconds_per_year = map(float, period_match.groups())
    fractional_period_trend = period_trend_seconds_per_year/(period_days*86400)
    q = donor/accretor
    # xdot is positive mass removed from the donor, in solar masses/year.
    conservative_coefficient = 3/donor-3/accretor
    conservative_rate = fractional_period_trend/conservative_coefficient
    rows = []
    for retained in [1, .75, .5, .25, 0]:
        for channel in ["accretor-reemission", "constant-gamma-4", "constant-gamma-8"]:
            gamma = q if channel == "accretor-reemission" else int(channel.rsplit("-", 1)[1])
            coefficient = (3/donor-3*retained/accretor
                           -(1-retained)*(3*gamma+1)/(donor+accretor))
            rows.append({"retained_fraction": retained, "channel": channel,
                         "positive_rate_solution": coefficient > 0,
                         "conditional_rate_solar_per_year": fractional_period_trend/coefficient if coefficient > 0 else None})
    # Fixed fitted separation and donor radius are consistency checks, not a new
    # measurement or claim that the asynchronous accretor's surface is Roche-like.
    separation = re.search(r"a_\{\\rm orb\}\{\\rm\[R_\{\\odot\}\]\}&([0-9.]+)\\pm", source)
    donor_radius = re.search(r"\\cal R_\{\\rm\{\}_\{c\}\}\{\\rm\[R_\{\\odot\}\]\}&([0-9.]+)\\pm", source)
    if not separation or not donor_radius:
        raise ValueError("Fixed source's geometry fields did not match")
    computed_radius = float(separation[1])*float(eggleton(q))
    return {"source": "Mennickent & Djurasevic 2013, arXiv1303.5812v1 Table 1 and section 4",
            "conservative_rate_solar_per_year": conservative_rate,
            "source_rounded_rate_solar_per_year": 2.2e-5,
            "relative_difference_from_source_rounded_rate": conservative_rate/2.2e-5-1,
            "donor_roche_radius_to_fitted_radius": computed_radius/float(donor_radius[1]),
            "conditional_loss_channel_scenarios": rows,
            "period_trend_uncertainty_available": False,
            "mass_covariance_available": False,
            "mass_sigma_solar": {"donor": donor_error, "accretor": accretor_error},
            "inference_boundary": "Published aggregate parameter replay; no photometry, eclipse-time refit, complete posterior, CE alpha, or absolute age inferred"}
