import os
import sys
import glob
from datetime import datetime
from decimal import Decimal, ROUND_HALF_UP

class ConsigliereBackupChecker:
    def __init__(self, backup_dir="/Users/bpa/ForesixaQuant/backup_vault"):
        """Initializes un-delayed file pointers inside your local file infrastructure."""
        self.backup_dir = backup_dir

    def execute_volumetric_storage_audit(self) -> dict:
        print("\n============================================================")
        print("     QZOTIC CONSIGLIERE: STORAGE ROTATION & METRIC CHECKER   ")
        print("============================================================")
        print(f"[INFO] Monitoring Active Vault Path : '{self.backup_dir}'")
        print(f"[INFO] System Execution Timestamp   : {datetime.now().strftime('%A, %B %d, %Y')}\n")

        if not os.path.exists(self.backup_dir):
            print(f" -> [HALTED] Audit blocked. Backup vault directory missing: {self.backup_dir}")
            print("============================================================\n")
            return {}

        # Query all existing snapshot database files chronologically natively on disk
        search_pattern = os.path.join(self.backup_dir, "qzotic_backup_*.db")
        backup_files = glob.glob(search_pattern)
        
        # Sort files chronologically (newest files bubble to the top)
        backup_files.sort(key=os.path.getmtime, reverse=True)
        total_backups = len(backup_files)

        if total_backups == 0:
            print(" -> [NOTICE] Storage vault contains 0 active snapshot database entries.")
            print("============================================================\n")
            return {"file_count": 0, "total_bytes": 0}

        print("1. ROTATION ARCHIVE EVALUATION (CHRONOLOGICAL AGE MATRIX)")
        
        total_vault_bytes = Decimal("0")
        size_anomaly_detected = False
        previous_size = None

        for index, filepath in enumerate(backup_files, 1):
            filename = os.path.basename(filepath)
            try:
                # Capture literal file allocation sizes using fixed-point byte accuracy metrics
                file_bytes = Decimal(str(os.path.getsize(filepath)))
                total_vault_bytes += file_bytes
                file_mb = (file_bytes / Decimal("1048576")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            except Exception as e:
                print(f"   - [IO ERROR] Failed to parse hardware descriptor rows for {filename}: {str(e)}")
                continue

            # Assign chronological lifecycle retention tags natively
            if index == 1:
                age_status = "CRITICAL_CURRENT_BASELINE"
            elif index == 2:
                age_status = "TRU_TRAILING_WEEK_2"
            elif index == 3:
                age_status = "TRU_TRAILING_WEEK_3"
            else:
                age_status = "EXPIRED_OVER_RETENTION_THRESHOLD"

            # Stateful Integrity Sizing Checks (Enforces strict variance limits)
            size_integrity = "[PASSED - STABLE SCALING]"
            if file_bytes == 0:
                size_integrity = "[CRITICAL FAULT - 0 BYTE FILE DETECTED]"
                size_anomaly_detected = True
            elif previous_size is not None:
                # Flag an operational anomaly if any trailing week snapshot spikes or drops by more than 20%
                variance_coefficient = abs(file_bytes - previous_size) / previous_size
                if variance_coefficient > Decimal("0.20"):
                    size_integrity = "[WARNING - VOLUMETRIC METRIC VARIANCE OUT OF BOUNDS]"
                    size_anomaly_detected = True

            previous_size = file_bytes

            print(f"   [FILE {index}] {filename}")
            print(f"            • Snapshot Storage Footprint : {file_mb} MB ({int(file_bytes):,} Bytes)")
            print(f"            • Chronological File Status  : {age_status}")
            print(f"            • Sizing Integrity Check     : {size_integrity}\n")

        total_vault_mb = (total_vault_bytes / Decimal("1048576")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

        print("2. VOLUMETRIC DISK SPACE & RETENTION SUMMARY")
        print(f"   - Total Retained Snapshot Count : {total_backups} / 3 Max Allocated Rows")
        print(f"   - Consolidated Vault Disk Ingress: {total_vault_mb} MB Total Storage Volume")
        print("============================================================")
        
        if size_anomaly_detected:
            print(" INTEGRITY RATING: CRITICAL_STORAGE_VARIANCE_DETECTED")
            print(" STATUS: RESOURCE ALLOCATION OUT OF BOUNDS. RE-RUN REPAIR DAEMONS.")
        else:
            print(" STATUS: VOLUMETRIC AUDIT PASSED. ROTATION INTEGRITY SECURED.")
        print("============================================================\n")

        return {
            "file_count": total_backups,
            "total_bytes": int(total_vault_bytes),
            "anomaly_flag": size_anomaly_detected
        }

if __name__ == "__main__":
    checker = ConsigliereBackupChecker()
    checker.execute_volumetric_storage_audit()
