"""
Database Backup & Disaster Recovery Utility for NGO Foundation.
Performs atomic, consistent online backups of the SQLite operational database
using SQLite's native backup API, computes checksums, verifies database integrity,
and provides an automated test restoration mode.
Fulfills SRS Section 16.2 (Backup, recovery, and maintenance) and Checklist items C4 & C11.
"""

import argparse
import hashlib
import os
import shutil
import sqlite3
import sys
from datetime import datetime, timezone


def compute_sha256(filepath):
    """
    Computes the cryptographic SHA-256 hash of a file for integrity verification.

    Args:
        filepath (str): Absolute or relative path to the file.

    Returns:
        str: Hexadecimal SHA-256 digest string.
    """
    hasher = hashlib.sha256()
    with open(filepath, 'rb') as f:
        while chunk := f.read(65536):
            hasher.update(chunk)
    return hasher.hexdigest()


def backup_database(db_path, backup_dir):
    """
    Performs an atomic, online backup of a SQLite database to the target directory.
    Uses sqlite3's backup() routine to ensure transactional consistency even during concurrent writes.

    Args:
        db_path (str): Path to the source SQLite database file.
        backup_dir (str): Directory where the backup snapshot should be written.

    Returns:
        str: Path to the created backup snapshot file.
    """
    if not os.path.isfile(db_path):
        raise FileNotFoundError(f"Source database file '{db_path}' was not found.")

    os.makedirs(backup_dir, exist_ok=True)
    timestamp = datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%SZ')
    backup_filename = f"ngo_db_backup_{timestamp}.sqlite"
    backup_path = os.path.join(backup_dir, backup_filename)

    print(f"[INFO] Initiating online backup of '{db_path}'...")
    # Open source connection and target backup connection
    src_conn = sqlite3.connect(db_path)
    dst_conn = sqlite3.connect(backup_path)

    try:
        # Perform the atomic page-by-page copy
        src_conn.backup(dst_conn)
        print(f"[SUCCESS] Database backup snapshot created at: {backup_path}")
    finally:
        dst_conn.close()
        src_conn.close()

    # Verify backup integrity
    verify_conn = sqlite3.connect(backup_path)
    try:
        cursor = verify_conn.cursor()
        cursor.execute("PRAGMA integrity_check;")
        result = cursor.fetchone()[0]
        if result != "ok":
            raise RuntimeError(f"Integrity check failed for backup! Result: {result}")
        print(f"[SUCCESS] Backup integrity check passed (Result: {result}).")
    finally:
        verify_conn.close()

    checksum = compute_sha256(backup_path)
    print(f"[INFO] Backup SHA-256 Digest: {checksum}")
    return backup_path


def test_restore(backup_path):
    """
    Tests the validity of a backup by restoring it to a temporary staging environment
    and validating table counts and schema definitions.

    Args:
        backup_path (str): Path to the backup snapshot to test.

    Returns:
        bool: True if restore and table inspection succeeds, False otherwise.
    """
    print(f"[INFO] Testing recovery procedure from '{backup_path}'...")
    if not os.path.isfile(backup_path):
        print(f"[ERROR] Backup snapshot '{backup_path}' does not exist.")
        return False

    temp_restored_db = backup_path + ".test_restore.tmp"
    try:
        shutil.copyfile(backup_path, temp_restored_db)
        conn = sqlite3.connect(temp_restored_db)
        cursor = conn.cursor()

        # Query all table names in restored database
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        tables = [row[0] for row in cursor.fetchall()]
        print(f"[SUCCESS] Restored test database successfully. Found {len(tables)} tables: {tables[:6]}...")

        # Run quick integrity check
        cursor.execute("PRAGMA quick_check;")
        status = cursor.fetchone()[0]
        conn.close()

        if status == "ok":
            print("[SUCCESS] Test restore completed with 0 errors. Recovery test PASSED.")
            return True
        else:
            print(f"[ERROR] Test restore quick_check failed: {status}")
            return False
    finally:
        if os.path.exists(temp_restored_db):
            os.remove(temp_restored_db)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="NGO Foundation SQLite Backup & Disaster Recovery")
    parser.add_argument('--db', default="instance/ngo.db", help="Path to SQLite database file")
    parser.add_argument('--backup-dir', default="instance/backups", help="Directory for backup storage")
    parser.add_argument('--test-restore', action='store_true', help="Run restoration verification test")

    args = parser.parse_args()
    try:
        # Default or provided database file path
        resolved_db = os.path.abspath(args.db)
        resolved_backup_dir = os.path.abspath(args.backup_dir)

        if not os.path.exists(resolved_db):
            print(f"[WARNING] Database '{resolved_db}' does not exist yet. Please run migrations first.")
            sys.exit(0)

        snapshot = backup_database(resolved_db, resolved_backup_dir)
        if args.test_restore:
            success = test_restore(snapshot)
            sys.exit(0 if success else 1)
    except Exception as e:
        print(f"[FATAL] Backup operation failed: {e}")
        sys.exit(1)
