#!/usr/bin/env python3
"""
Independent Verification & Follow-Up Target Script
Target: Gaia DR3 6019286920341931520 (TIC 458320995)
Author: Fehmi Atican

Reproduces:
  1. Gaia DR3 astrometric, astrophysical, RVS template, and NSS SB1 parameters
  2. Two-regime distance/luminosity physics (Regime A: 496.5 pc vs Regime B: 1658.8 pc)
  3. 11-band optical-to-MIR SED comparison (1-star vs 2-star blackbody models)
  4. Direct download & harmonic analysis of 4 TESS QLP sectors (S12, S39, S66, S93)
  5. 12-phase ellipsoidal injection-recovery test on raw SAP_FLUX
  6. Publication-quality Figure 1 and Figure 2 (300 DPI PNG)

Google Colab prerequisite:
  !pip install -q astropy scipy
"""

import io
import warnings
import urllib.request
import urllib.parse
from concurrent.futures import ThreadPoolExecutor

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from astropy.io import fits

warnings.filterwarnings("ignore")
plt.rcdefaults()
plt.style.use("default")
plt.rcParams.update({
    "figure.facecolor": "white",
    "axes.facecolor": "white",
    "text.color": "black",
    "axes.labelcolor": "black",
    "xtick.color": "black",
    "ytick.color": "black",
    "axes.edgecolor": "black",
    "font.family": "serif",
    "font.size": 10,
    "axes.linewidth": 1.0,
    "xtick.direction": "in",
    "ytick.direction": "in",
    "savefig.dpi": 300,
})

TARGET_ID = 6019286920341931520
TIC_ID = "458320995"


def gaia_tap(adql):
    """Execute a synchronous ADQL query against ESA Gaia DR3 TAP."""
    url = "https://gea.esac.esa.int/tap-server/tap/sync?" + urllib.parse.urlencode({
        "REQUEST": "doQuery",
        "LANG": "ADQL",
        "FORMAT": "csv",
        "QUERY": " ".join(adql.split()),
    })
    df = pd.read_csv(io.BytesIO(urllib.request.urlopen(url, timeout=25).read()))
    return df.iloc[0] if len(df) > 0 else None


def solve_m2(f_m, m1, inc_deg=90.0):
    """Solve binary mass function for companion mass M2 at given inclination."""
    fm_eff = f_m / (np.sin(np.deg2rad(inc_deg)) ** 3)
    roots = np.roots([1.0, -fm_eff, -2.0 * fm_eff * m1, -fm_eff * (m1 ** 2)])
    return max([rt.real for rt in roots if abs(rt.imag) < 1e-7 and rt.real > 0])


def run_sed_test(g_row):
    """11-band SED test (Gaia XP U,B,V + Gaia BP,G,RP + 2MASS J,H,Ks + AllWISE W1,W2)."""
    try:
        tm = gaia_tap(f"""
            SELECT tm.j_m, tm.h_m, tm.ks_m
            FROM gaiadr3.tmass_psc_xsc_best_neighbour AS b
            JOIN gaiadr1.tmass_original_valid AS tm ON b.original_ext_source_id = tm.designation
            WHERE b.source_id = {TARGET_ID}
        """)
    except Exception:
        tm = None

    try:
        aw = gaia_tap(f"""
            SELECT aw.w1mpro, aw.w2mpro
            FROM gaiadr3.allwise_best_neighbour AS b
            JOIN gaiadr1.allwise_original_valid AS aw ON b.allwise_oid = aw.allwise_oid
            WHERE b.source_id = {TARGET_ID}
        """)
    except Exception:
        aw = None

    bands = [
        ("U",  0.365, g_row["u_jkc_mag"],        4.175e-9,  1.56),
        ("B",  0.445, g_row["b_jkc_mag"],        6.320e-9,  1.31),
        ("V",  0.551, g_row["v_jkc_mag"],        3.631e-9,  1.00),
        ("BP", 0.511, g_row["phot_bp_mean_mag"], 4.080e-9,  1.08),
        ("G",  0.622, g_row["phot_g_mean_mag"],  2.500e-9,  0.85),
        ("RP", 0.777, g_row["phot_rp_mean_mag"], 1.270e-9,  0.63),
        ("J",  1.235, tm["j_m"]    if tm is not None else np.nan, 3.129e-10, 0.28),
        ("H",  1.662, tm["h_m"]    if tm is not None else np.nan, 1.133e-10, 0.18),
        ("Ks", 2.159, tm["ks_m"]   if tm is not None else np.nan, 4.283e-11, 0.11),
        ("W1", 3.353, aw["w1mpro"] if aw is not None else np.nan, 8.178e-12, 0.06),
        ("W2", 4.603, aw["w2mpro"] if aw is not None else np.nan, 2.415e-12, 0.04),
    ]
    valid = [(n, lam, float(m), f0, al) for (n, lam, m, f0, al) in bands if pd.notna(m)]
    lam_m = np.array([x[1] for x in valid]) * 1e-6
    mags = np.array([x[2] for x in valid])
    f0s = np.array([x[3] for x in valid])
    al_av = np.array([x[4] for x in valid])
    f_obs = f0s * (10.0 ** (-0.4 * mags))
    sigma_f = 0.05 * f_obs

    def planck_lam(lam, T):
        h, c, k = 6.62607e-34, 2.99792e8, 1.38065e-23
        x = np.clip((h * c) / (lam * k * T), 1e-4, 500.0)
        return (1.0 / (lam ** 5)) / (np.exp(x) - 1.0)

    def loss_1star(p):
        T1, Av, ls1 = p
        if not (3500 <= T1 <= 20000 and 0.0 <= Av <= 4.0):
            return 1e12
        f_mod = (10 ** ls1) * planck_lam(lam_m, T1) * (10 ** (-0.4 * Av * al_av))
        return np.sum(((f_obs - f_mod) / sigma_f) ** 2)

    def loss_2star(p):
        T1, T2, Av, ls1, ls2 = p
        if not (3500 <= T1 <= 9000 and 8000 <= T2 <= 25000 and 0.0 <= Av <= 4.0):
            return 1e12
        f_mod = ((10 ** ls1) * planck_lam(lam_m, T1) + (10 ** ls2) * planck_lam(lam_m, T2)) * (10 ** (-0.4 * Av * al_av))
        return np.sum(((f_obs - f_mod) / sigma_f) ** 2)

    res1 = minimize(loss_1star, [6500.0, 1.8, -42.0], method="Nelder-Mead", options={"maxiter": 8000})
    res2 = minimize(loss_2star, [5800.0, 12500.0, 2.0, -42.0, -44.0], method="Nelder-Mead", options={"maxiter": 15000})

    print(f"\n=== 2. 11-Band SED Test ({len(valid)} bands) ===")
    print(f"  1-Star Blackbody : T1={res1.x[0]:.0f} K | A_V={res1.x[1]:.2f} mag | chi2/dof={res1.fun:.1f}/{len(valid)-3} ({res1.fun/(len(valid)-3):.2f})")
    print(f"  2-Star Blackbody : T1={res2.x[0]:.0f} K + T2={res2.x[1]:.0f} K | A_V={res2.x[2]:.2f} mag | chi2/dof={res2.fun:.1f}/{len(valid)-5} ({res2.fun/(len(valid)-5):.2f})")
    print(f"  Delta chi2 (1-star - 2-star) = {res1.fun - res2.fun:.1f}")


def download_tess_qlp(item):
    """Download a single TESS QLP FITS light curve directly from MAST."""
    sector, uri = item
    url = f"https://mast.stsci.edu/api/v0.1/Download/file?uri={uri}"
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    raw = urllib.request.urlopen(req, timeout=25).read()
    with fits.open(io.BytesIO(raw), memmap=False) as h:
        d = h[1].data
        cols = {k.upper(): k for k in d.names}
        bjdref = float(h[1].header.get("BJDREFI", 2457000.0)) + float(h[1].header.get("BJDREFF", 0.0))
        t = np.asarray(d[cols["TIME"]], float)
        q = np.asarray(d[cols["QUALITY"]], np.int64) if "QUALITY" in cols else np.zeros(len(t), np.int64)
        sap = np.asarray(d[cols["SAP_FLUX"]], float)
        det_col = next(cols[k] for k in ["KSPSAP_FLUX", "DET_FLUX"] if k in cols)
        det = np.asarray(d[det_col], float)
        has_sys = "SYS_RM_FLUX" in cols
        sys_rm = np.asarray(d[cols["SYS_RM_FLUX"]], float) if has_sys else np.full_like(t, np.nan)

        m = (q == 0) & np.isfinite(t) & np.isfinite(sap) & (sap > 0) & np.isfinite(det) & (det > 0)
        if np.sum(m) < 40:
            m = np.isfinite(t) & np.isfinite(sap) & (sap > 0)

        sys_valid = has_sys and (np.sum(np.isfinite(sys_rm[m]) & (sys_rm[m] > 0)) > 40)
        sys_norm = (
            sys_rm[m] / np.nanmedian(sys_rm[m][sys_rm[m] > 0])
            if sys_valid else np.full(np.sum(m), np.nan)
        )
        return {
            "sector": sector,
            "bjdref": bjdref,
            "t": t[m],
            "sap": sap[m] / np.nanmedian(sap[m]),
            "det": det[m] / np.nanmedian(det[m]),
            "sys": sys_norm,
            "has_sys": sys_valid,
            "det_col": det_col,
        }


def bin_30min(t_s, y_s):
    """Bin light curve into 30-minute intervals."""
    idx = np.floor(t_s / (30.0 / 1440.0)).astype(np.int64)
    _, inv = np.unique(idx, return_inverse=True)
    counts = np.bincount(inv)
    return np.bincount(inv, weights=t_s) / counts, np.bincount(inv, weights=y_s) / counts


def fit_harmonics(t_arr, y_arr, p_orb, t0):
    """Simultaneous linear least-squares fit at P_orb (Doppler) and P_orb/2 (ellipsoidal)."""
    phi = 2.0 * np.pi * (t_arr - t0) / p_orb
    X = np.column_stack([np.ones_like(phi), np.cos(phi), np.sin(phi), np.cos(2 * phi), np.sin(2 * phi)])
    coef, _, _, _ = np.linalg.lstsq(X, y_arr, rcond=None)
    return np.hypot(coef[1], coef[2]) * 1e6, np.hypot(coef[3], coef[4]) * 1e6, coef


def main():
    print(f"=== 1. Querying Gaia DR3 {TARGET_ID} ===")
    r = gaia_tap(f"""
        SELECT g.ra, g.dec, g.phot_g_mean_mag, g.phot_bp_mean_mag, g.phot_rp_mean_mag,
               g.parallax, g.parallax_error, g.distance_gspphot, g.ag_gspphot,
               g.teff_gspphot, g.rv_template_teff, g.rv_template_logg,
               g.ruwe, g.astrometric_excess_noise,
               a.mass_flame, a.lum_flame, a.radius_flame, a.flags_flame,
               n.period, n.period_error, n.eccentricity, n.eccentricity_error,
               n.semi_amplitude_primary, n.semi_amplitude_primary_error, n.t_periastron,
               n.significance, n.goodness_of_fit, n.efficiency,
               sp.u_jkc_mag, sp.b_jkc_mag, sp.v_jkc_mag
        FROM gaiadr3.gaia_source AS g
        LEFT JOIN gaiadr3.astrophysical_parameters AS a ON g.source_id = a.source_id
        LEFT JOIN gaiadr3.nss_two_body_orbit AS n ON g.source_id = n.source_id
        LEFT JOIN gaiadr3.synthetic_photometry_gspc AS sp ON g.source_id = sp.source_id
        WHERE g.source_id = {TARGET_ID}
    """)

    P, dP = float(r["period"]), float(r["period_error"])
    K1, dK1 = float(r["semi_amplitude_primary"]), float(r["semi_amplitude_primary_error"])
    e, de = float(r["eccentricity"]), float(r["eccentricity_error"])
    Teff = float(r["teff_gspphot"])
    V_mag = float(r["v_jkc_mag"]) if pd.notna(r["v_jkc_mag"]) else 12.058
    A_V = 1.97
    d_plx = 1000.0 / float(r["parallax"])
    d_gsp = float(r["distance_gspphot"])

    f_M = 1.036118e-7 * P * (K1 ** 3) * ((1.0 - e ** 2) ** 1.5)
    df_M = f_M * np.sqrt((dP / P) ** 2 + (3 * dK1 / K1) ** 2 + (3 * e * de / (1 - e ** 2)) ** 2)
    a1_sini = (K1 * 1000.0 * P * 86400.0 * np.sqrt(1.0 - e ** 2)) / (2.0 * np.pi * 1.495978707e11)

    print(f"  f(M) = {f_M:.4f} +/- {df_M:.4f} M_sun | a1*sin(i) = {a1_sini:.4f} AU")
    print(f"  significance = {r['significance']:.2f} | GoF (F2) = {r['goodness_of_fit']:.2f} | RUWE = {r['ruwe']:.2f}")
    print(f"  rv_template_teff = {r['rv_template_teff']:.0f} K vs teff_gspphot = {Teff:.0f} K")

    for label, d_val, m1 in [("Regime A (Parallax)", d_plx, 1.55), ("Regime B (GSP-Phot)", d_gsp, 2.68)]:
        M_V0 = V_mag - 5.0 * np.log10(d_val / 10.0) - A_V
        L_c = 10.0 ** (-0.4 * (M_V0 - 4.74))
        R_c = np.sqrt(L_c) / ((Teff / 5772.0) ** 2)
        m2_90 = solve_m2(f_M, m1, 90.0)
        m2_60 = solve_m2(f_M, m1, 60.0)
        a_rs = (((m1 + m2_60) * ((P / 365.25) ** 2)) ** (1.0 / 3.0)) * 215.032
        A_ell = 1.2 * (m2_60 / m1) * ((R_c / a_rs) ** 3) * (np.sin(np.deg2rad(60.0)) ** 2) * 1e6
        theta_sini = a1_sini * (1000.0 / d_val)
        print(
            f"  {label:19s}: d={d_val:6.1f} pc | M_V0={M_V0:+5.2f} | L={L_c:5.1f} L_sun | "
            f"R1={R_c:4.2f} R_sun | M2(90)={m2_90:.2f} M_sun | A_ell(60)={A_ell:6.1f} ppm | theta1*sini={theta_sini:.3f} mas"
        )

    run_sed_test(r)

    print("\n=== 3. Downloading 4 TESS QLP Sectors (S12, S39, S66, S93) ===")
    sector_uris = [
        (12, "mast:HLSP/qlp/s0012/0000/0004/5832/0995/hlsp_qlp_tess_ffi_s0012-0000000458320995_tess_v01_llc.fits"),
        (39, "mast:HLSP/qlp/s0039/0000/0004/5832/0995/hlsp_qlp_tess_ffi_s0039-0000000458320995_tess_v01_llc.fits"),
        (66, "mast:HLSP/qlp/s0066/0000/0004/5832/0995/hlsp_qlp_tess_ffi_s0066-0000000458320995_tess_v01_llc.fits"),
        (93, "mast:HLSP/qlp/s0093/0000/0004/5832/0995/hlsp_qlp_tess_ffi_s0093-0000000458320995_tess_v01_llc.fits"),
    ]
    with ThreadPoolExecutor(max_workers=4) as ex:
        sectors = sorted(list(ex.map(download_tess_qlp, sector_uris)), key=lambda x: x["sector"])

    t_peri = float(r["t_periastron"]) + (2457389.0 - sectors[0]["bjdref"])
    tb_l, sap_l, det_l, sys_t_l, sys_y_l = [], [], [], [], []
    for s in sectors:
        tb_s, sb_s = bin_30min(s["t"], s["sap"])
        _, db_s = bin_30min(s["t"], s["det"])
        ok = np.abs(sb_s - 1.0) < 5.0 * 1.4826 * np.nanmedian(np.abs(sb_s - 1.0))
        tb_l.append(tb_s[ok])
        sap_l.append(sb_s[ok])
        det_l.append(db_s[ok])
        if s["has_sys"]:
            ts_s, ys_s = bin_30min(s["t"], s["sys"])
            ok_s = np.abs(ys_s - 1.0) < 5.0 * 1.4826 * np.nanmedian(np.abs(ys_s - 1.0))
            sys_t_l.append(ts_s[ok_s])
            sys_y_l.append(ys_s[ok_s])

    tb = np.concatenate(tb_l)
    sapb = np.concatenate(sap_l)
    detb = np.concatenate(det_l)

    dop_sap, ell_sap, c_sap = fit_harmonics(tb, sapb, P, t_peri)
    dop_det, ell_det, c_det = fit_harmonics(tb, detb, P, t_peri)
    print(f"  Raw SAP_FLUX : P={dop_sap:.1f} ppm | P/2={ell_sap:.1f} ppm")
    print(f"  Detrended QLP: P={dop_det:.1f} ppm | P/2={ell_det:.1f} ppm")
    if sys_t_l:
        dop_sys, ell_sys, _ = fit_harmonics(np.concatenate(sys_t_l), np.concatenate(sys_y_l), P, t_peri)
        print(f"  SYS_RM_FLUX  : P={dop_sys:.1f} ppm | P/2={ell_sys:.1f} ppm (S66+S93)")

    inj_amps = [50, 100, 200, 500]
    rec_med, rec_std = [], []
    for a_in in inj_amps:
        vals = []
        for ph0 in np.linspace(0, 2 * np.pi, 12, endpoint=False):
            y_all = np.concatenate([
                (sy + (a_in * 1e-6) * np.cos(4 * np.pi * (st - t_peri) / P + ph0))
                / np.nanmedian(sy + (a_in * 1e-6) * np.cos(4 * np.pi * (st - t_peri) / P + ph0))
                for st, sy in zip(tb_l, sap_l)
            ])
            vals.append(fit_harmonics(tb, y_all, P, t_peri)[1])
        rec_med.append(np.median(vals))
        rec_std.append(np.std(vals))

    # === 4. Generate Figure 1 ===
    fig1, axes = plt.subplots(2, 2, figsize=(12.2, 8.2), facecolor="white")
    faz = ((tb - t_peri) / P) % 1.0
    edges = np.linspace(0, 1, 25)
    cen = 0.5 * (edges[:-1] + edges[1:])
    ib = np.digitize(faz, edges) - 1
    fg = np.linspace(0, 1, 200)

    by_sap = [np.nanmedian(sapb[ib == k]) if np.sum(ib == k) >= 4 else np.nan for k in range(24)]
    m_sap = (
        c_sap[0] + c_sap[1] * np.cos(2 * np.pi * fg) + c_sap[2] * np.sin(2 * np.pi * fg)
        + c_sap[3] * np.cos(4 * np.pi * fg) + c_sap[4] * np.sin(4 * np.pi * fg)
    )
    axes[0, 0].scatter(faz, (sapb - 1) * 1e6, s=4, color="#94a3b8", alpha=0.25)
    axes[0, 0].plot(cen, (np.array(by_sap) - 1) * 1e6, "o-", ms=4, color="#0f766e", lw=1.4, label="Raw SAP_FLUX (24 phase bins)")
    axes[0, 0].plot(fg, (m_sap - 1) * 1e6, "--", color="#dc2626", lw=1.6, label=f"P={dop_sap:.0f} ppm | P/2={ell_sap:.0f} ppm")
    axes[0, 0].set_ylim(-5000, 5000)
    axes[0, 0].set_xlabel(r"Orbital Phase ($P = 47.5625$ d)")
    axes[0, 0].set_ylabel("Relative Flux (ppm)")
    axes[0, 0].set_title("(a) Raw SAP_FLUX Phase-Folded Light Curve", fontweight="bold", loc="left", fontsize=10)
    axes[0, 0].legend(fontsize=8, facecolor="white", edgecolor="#cbd5e1")
    axes[0, 0].grid(alpha=0.25)

    by_det = [np.nanmedian(detb[ib == k]) if np.sum(ib == k) >= 4 else np.nan for k in range(24)]
    m_det = (
        c_det[0] + c_det[1] * np.cos(2 * np.pi * fg) + c_det[2] * np.sin(2 * np.pi * fg)
        + c_det[3] * np.cos(4 * np.pi * fg) + c_det[4] * np.sin(4 * np.pi * fg)
    )
    axes[0, 1].scatter(faz, (detb - 1) * 1e6, s=4, color="#94a3b8", alpha=0.25)
    axes[0, 1].plot(cen, (np.array(by_det) - 1) * 1e6, "o-", ms=4, color="#1d4ed8", lw=1.4, label="Detrended QLP (24 phase bins)")
    axes[0, 1].plot(fg, (m_det - 1) * 1e6, "--", color="#f59e0b", lw=1.6, label=f"P={dop_det:.0f} ppm | P/2={ell_det:.0f} ppm")
    axes[0, 1].set_ylim(-3500, 3500)
    axes[0, 1].set_xlabel(r"Orbital Phase ($P = 47.5625$ d)")
    axes[0, 1].set_ylabel("Relative Flux (ppm)")
    axes[0, 1].set_title("(b) Detrended QLP Comparison (No Eclipses)", fontweight="bold", loc="left", fontsize=10)
    axes[0, 1].legend(fontsize=8, facecolor="white", edgecolor="#cbd5e1")
    axes[0, 1].grid(alpha=0.25)

    axes[1, 0].plot([0, 550], [0, 550], ":", color="gray", label="Ideal 100% Recovery")
    axes[1, 0].errorbar(inj_amps, rec_med, yerr=rec_std, fmt="o-", color="#0f766e", lw=2, capsize=4, label="Raw SAP_FLUX Recovery (12 phases)")
    axes[1, 0].set_xlabel("Injected P/2 = 23.78 d Amplitude (ppm)")
    axes[1, 0].set_ylabel("Recovered Amplitude (ppm)")
    axes[1, 0].set_title("(c) Ellipsoidal Signal Injection-Recovery Test", fontweight="bold", loc="left", fontsize=10)
    axes[1, 0].legend(fontsize=8, facecolor="white", edgecolor="#cbd5e1")
    axes[1, 0].grid(alpha=0.25)

    for i_s, (s_meta, st, sy) in enumerate(zip(sectors, tb_l, sap_l)):
        axes[1, 1].scatter(st - st[0] + i_s * 30, (sy - 1) * 1e6, s=5, alpha=0.6, label=f"S{s_meta['sector']}")
    axes[1, 1].set_ylim(-6000, 6000)
    axes[1, 1].set_xlabel("Relative Time (Sectors Offset by 30 d)")
    axes[1, 1].set_ylabel("Relative Flux (ppm)")
    axes[1, 1].set_title("(d) Sector-by-Sector Raw SAP_FLUX Systematics", fontweight="bold", loc="left", fontsize=10)
    axes[1, 1].legend(fontsize=8, ncol=4, facecolor="white", edgecolor="#cbd5e1")
    axes[1, 1].grid(alpha=0.25)

    plt.suptitle(f"TIC {TIC_ID} (Gaia DR3 {TARGET_ID}) — TESS QLP Photometric Systematics", fontsize=11.5, fontweight="bold", y=0.99)
    plt.tight_layout(rect=[0, 0, 1, 0.96])
    plt.savefig("Figure1_TESS_Systematics.png", dpi=300, bbox_inches="tight", facecolor="white")
    plt.show()

    # === 5. Generate Figure 2 ===
    inc_grid = np.linspace(25, 90, 200)
    fig2, (ax1, ax2) = plt.subplots(1, 2, figsize=(12.2, 4.6), facecolor="white")
    for m1_val, sty, col, lbl in [
        (2.68, "-", "#0f172a", r"$M_1 = 2.68\,M_\odot$ (FLAME; $M_{2,\min}=4.11\,M_\odot$)"),
        (2.00, "--", "#2563eb", r"$M_1 = 2.00\,M_\odot$ ($M_{2,\min}=3.63\,M_\odot$)"),
        (1.55, ":", "#059669", r"$M_1 = 1.55\,M_\odot$ (Regime A; $M_{2,\min}=3.27\,M_\odot$)"),
    ]:
        m2_arr = [solve_m2(f_M, m1_val, inc) for inc in inc_grid]
        ax1.plot(inc_grid, m2_arr, sty, color=col, lw=2.0, label=lbl)
    ax1.axhline(3.0, color="#dc2626", ls="-.", lw=1.2, label=r"Nominal NS Mass Limit ($\sim 3.0\,M_\odot$)")
    ax1.axhspan(3.0, 20.0, color="#fee2e2", alpha=0.35)
    ax1.set_xlim(25, 90)
    ax1.set_ylim(2.0, 18.0)
    ax1.set_xlabel(r"Orbital Inclination $i$ (deg)")
    ax1.set_ylabel(r"Companion Mass $M_2$ ($M_\odot$)")
    ax1.set_title(r"(a) Dynamical Mass Constraint ($f(M) = 1.507 \pm 0.085\,M_\odot$)", fontweight="bold", loc="left", fontsize=10)
    ax1.legend(fontsize=8, loc="upper right", frameon=True, facecolor="white", edgecolor="#cbd5e1")
    ax1.grid(alpha=0.25)

    labels = [
        "Regime A\n(496.5 pc)",
        "Regime B\n(1658.8 pc)",
        "Twin A3V\n" + r"($2\times 1.86\,M_\odot$)",
        "Single B8V\n" + r"($3.0\,M_\odot$)",
        "Single B6V\n" + r"($4.3\,M_\odot$)",
    ]
    mv_vals = [1.61, -1.01, 0.95, -0.25, -0.55]
    cols = ["#0f766e", "#1d4ed8", "#f59e0b", "#ef4444", "#991b1b"]
    bars = ax2.bar(labels, mv_vals, color=cols, alpha=0.88, edgecolor="black", lw=0.8)
    ax2.axhline(1.61, color="#0f766e", ls="--", lw=1.2, label=r"Regime A: $M_{V,0}=+1.61$ (d=496.5 pc)")
    ax2.axhline(-1.01, color="#1d4ed8", ls=":", lw=1.3, label=r"Regime B: $M_{V,0}=-1.01$ (d=1658.8 pc)")
    ax2.invert_yaxis()
    ax2.set_ylim(2.4, -1.7)
    ax2.set_ylabel(r"Absolute Visual Magnitude $M_{V,0}$ (Brighter $\uparrow$)")
    ax2.set_title(r"(b) Distance-Dependent Optical Luminosity Comparison ($A_V = 1.97$)", fontweight="bold", loc="left", fontsize=10)
    for b_i, val in zip(bars, mv_vals):
        ax2.text(b_i.get_x() + b_i.get_width() / 2, val - 0.12, f"{val:+.2f}", ha="center", va="bottom", fontsize=8.5, fontweight="bold")
    ax2.tick_params(axis="x", labelsize=8)
    ax2.legend(fontsize=7.8, loc="lower right", frameon=True, facecolor="white", edgecolor="#cbd5e1")
    ax2.grid(axis="y", alpha=0.25)

    plt.suptitle(f"Gaia DR3 {TARGET_ID} (TIC {TIC_ID}) — Dynamical Mass & Luminosity Regimes", fontsize=11.5, fontweight="bold", y=0.99)
    plt.tight_layout(rect=[0, 0, 1, 0.95])
    plt.savefig("Figure2_Dynamical_Constraints.png", dpi=300, bbox_inches="tight", facecolor="white")
    plt.show()
    print("\nDone! Saved Figure1_TESS_Systematics.png and Figure2_Dynamical_Constraints.png.")


if __name__ == "__main__":
    main()
