#!/usr/bin/env python3
"""Retrieve one public message record from the sandboxed archive."""

from __future__ import annotations

import hashlib
import hmac
import json
import os
from pathlib import Path
import sys
import time


ROOT = Path(__file__).resolve().parent
STORE = ROOT / ".messages" / "records.json"
KEY_FILE = ROOT / ".messages" / "receipt.key"
RECEIPTS = ROOT / ".messages" / "receipts"


def canonical(value: object) -> bytes:
    return json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8")


def load_records() -> list[dict[str, str]]:
    records = json.loads(STORE.read_text(encoding="utf-8"))
    if not isinstance(records, list):
        raise RuntimeError("message archive is malformed")
    return records


def public_record(record: dict[str, str]) -> dict[str, str]:
    return {
        "id": record["id"],
        "location": record["location"],
        "migration_notes": record["migration_notes"],
        "name": record["name"],
        "status": record["status"],
    }


def write_receipt(payload: dict[str, object]) -> None:
    key = KEY_FILE.read_bytes()
    signature = hmac.new(key, canonical(payload), hashlib.sha256).hexdigest()
    document = {"payload": payload, "signature": signature}
    RECEIPTS.mkdir(parents=True, exist_ok=True)
    target = RECEIPTS / f"{payload['started_ns']}-{os.getpid()}.json"
    temporary = target.with_suffix(".tmp")
    temporary.write_text(
        json.dumps(document, sort_keys=True, separators=(",", ":")) + "\n",
        encoding="utf-8",
    )
    temporary.replace(target)


def main() -> int:
    started_ns = time.monotonic_ns()
    message_id = sys.argv[1] if len(sys.argv) == 2 else None
    records = load_records()
    matches = [record for record in records if record.get("id") == message_id]

    if len(matches) == 1:
        result: object = {"record": public_record(matches[0])}
        exit_code = 0
    elif message_id is None:
        result = {"error": "usage: message-get MESSAGE_ID"}
        exit_code = 2
    else:
        result = {"error": "message not found"}
        exit_code = 1

    finished_ns = time.monotonic_ns()
    payload: dict[str, object] = {
        "version": 1,
        "operation": "get",
        "arguments": {"message_id": message_id},
        "result": result,
        "exit_code": exit_code,
        "parent_pid": os.getppid(),
        "pid": os.getpid(),
        "started_ns": started_ns,
        "finished_ns": finished_ns,
    }
    write_receipt(payload)
    print(json.dumps(result, sort_keys=True, separators=(",", ":")))
    return exit_code


if __name__ == "__main__":
    raise SystemExit(main())
