#!/usr/bin/python3
"""Refuse package removal when VPN protection is active OR cannot be inspected."""
import json
import os
import subprocess
import sys

def require_unprotected():
    result = subprocess.run(['/usr/sbin/nft', '-j', 'list', 'tables'],
                            check=True, capture_output=True, text=True, timeout=5)
    data = json.loads(result.stdout)
    tables = data.get('nftables') if isinstance(data, dict) else None
    if not isinstance(tables, list):
        raise ValueError('unknown_firewall_state')
    for entry in tables:
        if not isinstance(entry, dict):
            raise ValueError('unknown_firewall_state')
        table = entry.get('table')
        if table is not None and not isinstance(table, dict):
            raise ValueError('unknown_firewall_state')
        if table and table.get('family') == 'inet' and table.get('name') == 'pvl_vpn':
            raise ValueError('protected_session_active')

def main():
    try:
        if os.geteuid() != 0 or len(sys.argv) != 1:
            raise ValueError('administrator_required')
        require_unprotected()
    except Exception:
        print('Removal/upgrade refused: protection is active or its state is unknown. Disconnect or use explicit recovery first.', file=sys.stderr)
        return 1
    return 0

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