"""Replay a single synthetic P-401 reading with the published classifier, offline."""
import argparse
import csv
import hashlib
import io
import json
from pathlib import Path
import sys
import types
import zipfile


ARCHIVE_SHA = "037a911454af5f4ffdb2c79011c6e64f592c132e4405156e149e8280f123cf40"
COMMIT = "e7844abd43d16f63e0f8948519e8ea8cc22de09a"
ROOT = "LangGraph-based-LNG-Plant-Operations-Copilot-" + COMMIT + "/"
TAG = "P-401-VIB"


def replay(archive_path, timestamp, count):
    data = archive_path.read_bytes()
    if hashlib.sha256(data).hexdigest() != ARCHIVE_SHA:
        raise ValueError("Source ZIP SHA-256 mismatch. Download the fixed commit.")
    with zipfile.ZipFile(io.BytesIO(data)) as archive:
        tag = json.loads(archive.read(ROOT + "sample-data/equipment/p401_vibration.json"))
        csv_rows = csv.DictReader(io.StringIO(archive.read(ROOT + "sample-data/sensor_readings.csv").decode()))
        rows = sorted((r for r in csv_rows if r["tag_id"] == TAG), key=lambda r: r["timestamp"])
        original = archive.read(ROOT + "backend/app/tools/anomaly_detection.py")
    times = [r["timestamp"] for r in rows]
    if times.count(timestamp) != 1:
        raise ValueError("No unique P-401-VIB reading at this UTC time; check the source CSV.")
    index = times.index(timestamp)
    history = rows[max(0, index - count):index]
    # Only the pinned standard-library classifier runs. No API, graph or DB starts.
    detector = types.ModuleType("offline_lng_anomaly_detection")
    sys.modules[detector.__name__] = detector
    exec(compile(original, "pinned-anomaly-detection.py", "exec"), detector.__dict__)
    current = float(rows[index]["value"])
    config = {k: tag[k] for k in ("normal_min", "normal_max", "critical_min", "critical_max",
                                  "warning_z", "warning_rate_per_hour")}
    result = detector.classify_reading(current_value=current, history=[
        detector.Reading(timestamp=r["timestamp"], value=float(r["value"])) for r in history
    ], **config)
    return dict(sourceCommit=COMMIT, dataset="upstream synthetic sample", equipment=tag["equipment_id"],
                tag=TAG, unit=tag["unit"], timestamp=timestamp, value=current, config=config,
                requestedHistory=count, historyCount=len(history), historyStart=history[0]["timestamp"] if history else None,
                historyEnd=history[-1]["timestamp"] if history else None, lastReadings=history[-6:] + [rows[index]],
                classifierOutput={"classification": result.classification, **result.to_dict()},
                confirmedCause=None, fieldVerification=None)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("archive", type=Path)
    parser.add_argument("timestamp")
    parser.add_argument("out", type=Path)
    parser.add_argument("--history", type=int, choices=(0, 168), default=168,
                        help="168 prior records, or 0 to test a missing handoff history")
    args = parser.parse_args()
    if args.out.exists():
        raise ValueError("Choose a new output filename; the earlier handoff was preserved.")
    record = replay(args.archive, args.timestamp, args.history)
    with args.out.open("x", encoding="utf-8") as out:
        json.dump(record, out, indent=2, ensure_ascii=False)
        out.write("\n")
    signal = record["classifierOutput"]
    print(record["timestamp"], record["value"], record["unit"], record["historyCount"],
          signal["classification"], signal["threshold_breach"], signal["stuck_detected"])
    print(*signal["reasons"], sep="\n")


if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, KeyError) as error:
        sys.exit(str(error))
