#!/usr/bin/env python3
"""Rewrap synchronized Draft rows under the configured active encryption key."""

from __future__ import annotations

import json
import os
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from src.unfiled_draft_store import (  # noqa: E402
    UnfiledDraftEncryptionError,
    UnfiledDraftStore,
    decode_unfiled_draft_encryption_keyring,
)


def main() -> int:
    try:
        keys, active = decode_unfiled_draft_encryption_keyring(
            os.getenv("STACKCHAIN_UNFILED_DRAFT_ENCRYPTION_KEYS", ""),
            os.getenv("STACKCHAIN_UNFILED_DRAFT_ACTIVE_KEY_ID", ""),
        )
        store = UnfiledDraftStore(
            os.getenv(
                "STACKCHAIN_UNFILED_DRAFT_DB",
                str(Path(os.getenv("STACKCHAIN_STATE_DIR", ".")) / "unfiled-drafts.sqlite3"),
            ),
            encryption_keys=keys,
            active_key_id=active,
        )
        result = store.rewrap_all()
    except (OSError, UnfiledDraftEncryptionError):
        print(json.dumps({"error": "Draft rotation configuration is unavailable"}, sort_keys=True))
        return 2
    print(json.dumps(result, sort_keys=True))
    return 1 if result["failed"] else 0


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