""" sfm/mlg_ingest.py — take in one Blastware .MLG: verify it, work out its unit, keep the original, store its records once. Shared by POST /db/import/mlg_file and scripts/import_mlg_dir.py. Spec: docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md §3, §5, §6. """ from __future__ import annotations import datetime import hashlib import logging from pathlib import Path from typing import Optional from minimateplus.mlg_file import MlgFormatError, parse_mlg log = logging.getLogger("sfm.mlg_ingest") def resolve_serial( file_name: str, header_serial: Optional[str], hint: Optional[str], known: set[str], ) -> Optional[str]: """The unit a .MLG belongs to. The serial inside the file wins; then the caller's hint. An empty file carries none, and its name is with nothing between, so take the longest serial SFM already knows that the name starts with, followed only by digits (or nothing: DL2's first file was BE8081.MLG). None when nothing fits.""" if header_serial: return header_serial if hint: return hint stem = Path(file_name).name if stem.upper().endswith(".MLG"): stem = stem[:-4] def fits(serial: str) -> bool: counter = stem[len(serial):] return stem.upper().startswith(serial.upper()) and (counter == "" or counter.isdigit()) candidates = [s for s in known if fits(s)] return max(candidates, key=len) if candidates else None def ingest_mlg( db, store, file_name: str, data: bytes, *, serial_hint: Optional[str] = None, file_mtime: Optional[datetime.datetime] = None, call_in: bool = True, ) -> dict: """Ingest one .MLG. Never raises for a bad file: the result says what happened. status "error": not a whole .MLG, or any record fails its checksum — nothing of it is stored. status "duplicate": this name with these bytes is already stored. status "ok": the original is kept and its new records stored.""" result = { "filename": file_name, "status": "error", "detail": None, "serial": None, "serial_unresolved": False, "empty": False, "records": 0, "inserted": 0, "skipped": 0, "file_id": None, } try: mlg = parse_mlg(data) except MlgFormatError as exc: result["detail"] = str(exc) return result result["records"] = len(mlg.records) result["empty"] = mlg.empty if mlg.crc_failures: result["detail"] = ", ".join(f"record {i}" for i in mlg.crc_failures) + " fails its checksum" return result serial = resolve_serial(file_name, mlg.serial, serial_hint, db.known_serials()) result["serial"] = serial result["serial_unresolved"] = serial is None sha256 = hashlib.sha256(data).hexdigest() if db.mlg_file_exists(file_name, sha256): result["status"] = "duplicate" result["detail"] = "this file is already stored" return result stored_path = store.save_mlg(serial, file_name, data) file_id, inserted, skipped = db.insert_mlg( serial=serial, file_name=file_name, sha256=sha256, size=len(data), empty=mlg.empty, call_in=call_in, file_mtime=file_mtime, stored_path=stored_path, records=mlg.records, ) if file_id is None: # stored between the check and the insert result["status"] = "duplicate" result["detail"] = "this file is already stored" return result result.update(status="ok", file_id=file_id, inserted=inserted, skipped=skipped) log.info("mlg %s serial=%s inserted=%d skipped=%d", file_name, serial, inserted, skipped) return result