"""Extract the frozen observed TESS light curve using only Python's standard library."""
import argparse
import csv
import hashlib
import json
import math
from pathlib import Path

SCRIPT_DIRECTORY = Path(__file__).resolve().parent
ROOT = SCRIPT_DIRECTORY.parents[2] if len(SCRIPT_DIRECTORY.parents) > 2 else SCRIPT_DIRECTORY
SIDECAR = SCRIPT_DIRECTORY / 'tess-tic25155310-sector1.json'
DATA = SIDECAR if SIDECAR.exists() else ROOT / 'src/features/labs/stellar-photometry/data/tess-tic25155310-sector1.json'
DEFAULT_OUTPUT = SCRIPT_DIRECTORY / 'reproduced' if SIDECAR.exists() else ROOT / 'docs/astronomy/ac02/tutorial-output'
EXPECTED_SHA256 = 'a4c7eeec821d2c76f25f5e9495bc61411cf91abd2028bc0ce1e743b8971d2222'

def extract(output, input_path=DATA):
    payload = input_path.read_bytes()
    if hashlib.sha256(payload).hexdigest() != EXPECTED_SHA256:
        raise ValueError('Frozen subset checksum mismatch.')
    source = json.loads(payload)
    aperture = [(y, x) for y, row in enumerate(source['apertureMask']) for x, value in enumerate(row) if value & 2]
    results = []
    for record in source['records']:
        valid = record['TIME'] is not None and all(record[column][y][x] is not None for column in ['FLUX', 'FLUX_ERR', 'FLUX_BKG', 'FLUX_BKG_ERR'] for y, x in aperture)
        summed = lambda column: sum(record[column][y][x] for y, x in aperture) if valid else None
        flux = summed('FLUX')
        uncertainty = math.sqrt(sum(record['FLUX_ERR'][y][x] ** 2 for y, x in aperture)) if valid else None
        # Deliberately wrong column makes double subtraction observable without corrupting the result.
        background = summed('FLUX_BKG')
        results.append({'source_row': record['sourceRow'], 'cadence': record['CADENCENO'], 'time_btjd_days': record['TIME'], 'quality': record['QUALITY'], 'accepted': int(valid and record['QUALITY'] == 0), 'aperture_pixels': len(aperture), 'flux_e_per_s': flux, 'independent_pixel_error_e_per_s': uncertainty, 'spoc_background_e_per_s': background, 'wrong_double_subtracted_e_per_s': flux - background if valid else None})
    accepted_fluxes = sorted(row['flux_e_per_s'] for row in results if row['accepted'])
    median = (accepted_fluxes[(len(accepted_fluxes) - 1) // 2] + accepted_fluxes[len(accepted_fluxes) // 2]) / 2
    for row in results:
        row['relative_flux'] = row['flux_e_per_s'] / median if row['flux_e_per_s'] is not None else None
    output.mkdir(parents=True, exist_ok=True)
    csv_path = output / 'tess-aperture-lightcurve.csv'
    with csv_path.open('w', newline='') as stream:
        writer = csv.DictWriter(stream, fieldnames=list(results[0]), lineterminator='\n'); writer.writeheader(); writer.writerows(results)
    summary = {'subset_sha256': hashlib.sha256(payload).hexdigest(), 'source_sha256': source['provenance']['sourceSha256'], 'rows': len(results), 'accepted_quality_zero': len(accepted_fluxes), 'rejected_or_missing': len(results) - len(accepted_fluxes), 'aperture_pixels': len(aperture), 'median_accepted_flux_e_per_s': median, 'quality_policy': 'QUALITY == 0 and finite TIME, FLUX, FLUX_ERR, FLUX_BKG and FLUX_BKG_ERR in every aperture pixel; retain all rows in CSV.', 'error_model': 'Quadrature of supplied FLUX_ERR; interpixel correlations and additional systematics omitted.', 'sampling': 'Sparse every-400th-row teaching subset with first flagged examples. Not suitable for transit detection, completeness, or uninterrupted light-curve analysis.'}
    (output / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n')
    print(json.dumps(summary))
    return summary

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--input', type=Path, default=DATA)
    parser.add_argument('--out', type=Path, default=DEFAULT_OUTPUT)
    arguments = parser.parse_args()
    extract(arguments.out, arguments.input)
