from pathlib import Path
from tempfile import TemporaryDirectory

from django.core.management.base import BaseCommand, CommandError

from ._dbutils import decrypt_backup_to, pg_env, pg_config, require_binary, run_checked, sha256_file


class Command(BaseCommand):
    help = "Verify that a PostgreSQL custom-format backup is readable and matches its mandatory SHA-256 sidecar."

    def add_arguments(self, parser):
        parser.add_argument("file")

    def handle(self, *args, **options):
        path = Path(options["file"]).expanduser().resolve()
        if not path.is_file():
            raise CommandError(f"Backup not found: {path}")
        pg_restore = require_binary("pg_restore")
        digest = sha256_file(path)
        sha_file = Path(str(path) + ".sha256")
        if not sha_file.is_file():
            raise CommandError("Mandatory SHA-256 sidecar is missing. Do not restore an unverified backup.")
        expected = sha_file.read_text().strip().split()[0]
        if expected != digest:
            raise CommandError("SHA-256 mismatch. Do not restore this backup.")
        with TemporaryDirectory(prefix="hrpay-verify-") as tmp:
            plaintext = Path(tmp) / "verified.dump"
            decrypt_backup_to(path, plaintext)
            run_checked([pg_restore, "--list", str(plaintext)], env=pg_env(pg_config()))
        self.stdout.write(self.style.SUCCESS(f"Backup verified: {path}"))
        self.stdout.write(f"SHA256: {digest}")
