"""Select original stored JSON from a stopped, task-owned cage receipt database.

Selection does not verify a signature. Supply independent policy and executable
pins to `chio receipt verify-native-start` after preserving these original bytes.
"""
import argparse
import json
import os
from pathlib import Path
import sqlite3

p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--database', type=Path, required=True)
p.add_argument('--receipt-id', help='Required if the store contains more than one enforced launch')
p.add_argument('--output', type=Path, required=True)
a = p.parse_args()
os.umask(0o077)
# mode=ro refuses a missing database; selection never provisions an empty store.
with sqlite3.connect(a.database.resolve(strict=True).as_uri() + '?mode=ro', uri=True) as db:
    rows = db.execute('SELECT receipt_id, raw_json FROM chio_tool_receipts ORDER BY seq')
    selected = []
    for receipt_id, raw in rows:
        data = raw.encode() if isinstance(raw, str) else raw
        value = json.loads(data)
        body = value.get('action', {}).get('parameters', {})
        if (value.get('id') == receipt_id and body.get('stage') == 'enforcement'
                and body.get('state') == 'fully_enforced'
                and (a.receipt_id is None or receipt_id == a.receipt_id)):
            selected.append((receipt_id, data))
if len(selected) != 1:
    raise SystemExit(f'Expected one selected enforced launch; found {len(selected)}. Select the original receipt ID explicitly.')
receipt_id, original = selected[0]
with a.output.open('xb') as stream:
    stream.write(original)
print(receipt_id)
