"""Bounded artifact diagnostics with persisted domestic verification results."""
from InvestmentManager.export_engine.gallery import GalleryError
from contextlib import contextmanager
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import struct
import zipfile

from modules.core import storage_paths
from . import domestic_packages as preparation
from . import domestic_dictionaries as dictionaries
from . import domestic_batch_limits as limits
from . import export_performance as performance

MAX_SCAN = 2000
MAX_MANIFEST = 64 * 1024
MAX_METADATA = 8 * 1024 * 1024
MAX_ZIP = 128 * 1024 * 1024
MAX_UNPACKED = 256 * 1024 * 1024
MAX_ENTRY = 64 * 1024 * 1024
MAX_ZIP_ENTRIES = 1024
MAX_INPUT_FILE = 50 * 1024 * 1024
MAX_INPUT_TOTAL = 256 * 1024 * 1024
MAX_INPUT_ENTRIES = 4096
ID = re.compile(r'^[a-f0-9]{32}$')
SHA = re.compile(r'^[a-f0-9]{64}$')
ZIP_NAME = re.compile(r'^[A-Za-z0-9_.-]{1,120}\.zip$')
VERSION = re.compile(r'^[A-Za-z0-9+._-]{1,64}$')
STATES = {'READY', 'STALE', 'INVALID', 'BLOCKED'}


class CatalogError(Exception):
    def __init__(self, message, status=400):
        super().__init__(message)
        self.status = status


def _reason(code, message):
    return {'code': code, 'message': message}


def _unreadable(exc):
    return isinstance(exc,OSError) and not isinstance(exc,(FileNotFoundError,NotADirectoryError))


def _root(domain='domestic'):
    limits.check('artifact_root')
    if domain not in {'domestic', 'foreign'}: raise CatalogError('Nieznana domena paczki.')
    root = storage_paths.data_dir()
    if root is None or not root.is_dir():
        raise CatalogError('Brak zewnętrznego magazynu paczek.', 503)
    root = root.resolve()
    if root.is_relative_to(storage_paths.repo_root().resolve()):
        raise CatalogError('Magazyn paczek musi być prywatny.', 503)
    base = root/'exports'/domain
    for path in (root/'exports', base):
        if _link(path) or not path.resolve().is_relative_to(root):
            raise CatalogError('Niebezpieczna ścieżka magazynu.', 503)
        if domain=='foreign' and path.exists() and os.name!='nt' and path.stat().st_mode & 0o077:
            raise CatalogError('Magazyn zagraniczny wymaga prywatnych uprawnień.',503)
    return root, base


def _link(path):
    return path.is_symlink() or getattr(path, 'is_junction', lambda: False)()


def _safe(path, base):
    if _link(path) or not path.resolve().is_relative_to(base.resolve()):
        raise ValueError('Unsafe package path')


@contextmanager
def _open(path, base):
    _safe(path, base)
    before = path.lstat()
    if not stat.S_ISREG(before.st_mode):
        raise ValueError('Not a regular artifact file')
    flags = os.O_RDONLY | getattr(os, 'O_BINARY', 0) | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0)
    fd = os.open(path, flags)
    with os.fdopen(fd, 'rb') as stream:
        actual = os.fstat(stream.fileno())
        _safe(path, base)
        if not stat.S_ISREG(actual.st_mode) or (before.st_dev, before.st_ino) != (actual.st_dev, actual.st_ino):
            raise ValueError('Artifact changed during open')
        yield stream
        after = os.fstat(stream.fileno())
        current = path.lstat()
        _safe(path, base)
        identity=lambda info:(info.st_dev,info.st_ino,info.st_size,info.st_mtime_ns)
        if identity(actual)!=identity(after) or identity(actual)!=identity(current):
            raise ValueError('Artifact changed while reading')


def _date(value):
    if not isinstance(value, str) or len(value) > 64:
        raise ValueError('Invalid date')
    date = datetime.fromisoformat(value)
    if date.tzinfo is None or date.utcoffset() is None:
        raise ValueError('Missing timezone')
    return date


def _manifest(body, package_id, domain='domestic'):
    def unique(pairs):
        result = {}
        for key, value in pairs:
            if key in result: raise ValueError('Duplicate JSON key')
            result[key] = value
        return result
    item = json.loads(body, object_pairs_hook=unique)
    if not isinstance(item, dict): raise ValueError('Invalid manifest')
    if domain == 'foreign':
        from .foreign_contract import validate_manifest
        validate_manifest(item)
        if item['package_id'] != package_id: raise ValueError('Invalid identity')
        return item
    if domain != 'domestic': raise ValueError('Unknown domain')
    if type(item.get('schema_version')) is not int or item['schema_version'] != 1:
        raise ValueError('Unsupported schema')
    if item.get('domain','domestic')!='domestic': raise ValueError('Conflicting domestic domain')
    if item.get('package_id') != package_id or type(item.get('offer_id')) is not int or not 0 < item['offer_id'] <= 2**63-1:
        raise ValueError('Invalid identity')
    if item.get('portal') not in preparation.PORTALS or item.get('action') not in {'add', 'delete'}:
        raise ValueError('Invalid selection')
    if item.get('status') != 'prepared': raise ValueError('Invalid preparation status')
    _date(item.get('prepared_at'))
    if not isinstance(item.get('zip_name'), str) or not ZIP_NAME.fullmatch(item['zip_name']) or '..' in item['zip_name']:
        raise ValueError('Invalid ZIP name')
    if type(item.get('zip_size')) is not int or not 0 < item['zip_size'] <= MAX_ZIP:
        raise ValueError('Unsupported ZIP size')
    for field in ('zip_sha256', 'input_fingerprint'):
        if not isinstance(item.get(field), str) or not SHA.fullmatch(item[field]): raise ValueError('Invalid digest')
    context = item.get('generation_context')
    if isinstance(context, dict) and 'input_projection' in context and (type(context['input_projection']) is not int or context['input_projection'] != 2):
        raise ValueError('Unsupported input projection')
    if not isinstance(context, dict) or type(context.get('schema')) is not int or context['schema'] != 1:
        raise ValueError('Invalid generation context')
    if context.get('portal') != item['portal'] or context.get('action') != item['action']:
        raise ValueError('Context selection mismatch')
    gen = context.get('generator')
    if not isinstance(gen, dict) or set(gen) != {'engine_sha256','python','jinja2','pillow'}:
        raise ValueError('Invalid generator identity')
    if not isinstance(gen['engine_sha256'], str) or not SHA.fullmatch(gen['engine_sha256']): raise ValueError('Invalid version digest')
    if any(not isinstance(gen[k], str) or not VERSION.fullmatch(gen[k]) for k in ('python','jinja2','pillow')):
        raise ValueError('Invalid versions')
    if not isinstance(context.get('website_base_url'), str) or not 0 < len(context['website_base_url']) <= 2048:
        raise ValueError('Invalid website context')
    company = context.get('company_settings')
    if not isinstance(company, dict) or any(k not in preparation.COMPANY_KEYS or not isinstance(v,str) or len(v)>512 for k,v in company.items()):
        raise ValueError('Invalid company context')
    rows = context.get('dictionaries')
    if not isinstance(rows, list): raise ValueError('Invalid dictionaries')
    expected = list(dictionaries.URLS) if item['portal'] == 'domiporta' else []
    if len(rows) != len(expected): raise ValueError('Incomplete dictionary context')
    for row, url in zip(rows, expected):
        if not isinstance(row,dict) or row.get('url') != url or row.get('status') not in {'available','unavailable_fallback'}:
            raise ValueError('Invalid dictionary context')
        if row['status'] == 'available' and (not isinstance(row.get('sha256'),str) or not SHA.fullmatch(row['sha256'])
            or type(row.get('size')) is not int or not 0 < row['size'] <= dictionaries.MAX_BYTES):
            raise ValueError('Invalid dictionary hash')
    return item


def _empty(package_id):
    return {'package_id': package_id, 'offer_id': None, 'portal': None, 'action': None, 'prepared_at': None,
            'state': 'BLOCKED', 'reasons': [], 'warnings': [], 'verification_required': True,
            'checked_at': None, 'transport_eligible': False}


def package_folder(base, package_id, domain='domestic', *, locations=None):
    if domain == 'foreign':
        return base/package_id
    from .domestic_storage import folder
    return folder(base, package_id, locations=locations)


def _package_exists(base, package_id, domain='domestic'):
    try:
        path = package_folder(base, package_id, domain)
        return _link(path) or path.exists()
    except ValueError:
        return True  # diagnose unsafe/ambiguous storage, never follow it


def _metadata(base, package_id, domain='domestic', *, folder=None, locations=None):
    result = _empty(package_id)
    if domain=='foreign':result['domain']='foreign'
    try:
        folder = folder if folder is not None else package_folder(base, package_id, domain, locations=locations)
        _safe(folder, base)
        if not folder.is_dir(): raise ValueError('Invalid package directory')
        if domain=='foreign' and os.name!='nt' and folder.stat().st_mode & 0o077:
            raise ValueError('Unsafe directory permissions')
        with _open(folder/'manifest.json', base) as stream:
            raw = stream.read(MAX_MANIFEST+1)
        if len(raw)>MAX_MANIFEST: raise ValueError('Manifest limit exceeded')
        item = _manifest(raw, package_id, domain)
        if domain == 'domestic' and base.name == 'domestic' and folder != base/package_id:
            from .domestic_storage import structured, safe
            safe(folder, base)
            if structured(base, item) != folder:
                raise ValueError('Artifact directory/manifest binding mismatch')
        result.update({k:item[k] for k in ('portal','action','prepared_at')})
        if domain == 'foreign':
            result.update(domain='foreign', subject=item['subject'], members=item['members'],
                          offer_id=item['subject']['id'] if item['subject']['kind']=='foreign_offer' else None,
                          manifest=item, transport_profile=item['transport_profile'])
        else: result['offer_id'] = item['offer_id']
        result['artifact'] = {k:item[k] for k in ('zip_name','zip_size','zip_sha256','input_fingerprint')}
        result['generator'] = (dict(item['generation_context']['versions'], engine_sha256=item['generation_context']['engine_sha256'])
                               if domain=='foreign' else item['generation_context']['generator'])
        result['dictionary_context'] = [{k:v for k,v in d.items() if k in {'url','status','sha256','size'}}
                                        for d in item['generation_context'].get('dictionaries',[])]
        # Lightweight metadata only. Existence/size can disprove validity,
        # but cannot establish checksum, integrity or freshness.
        path = folder/item['zip_name']
        _safe(path, base)
        info = path.lstat()
        if domain=='foreign' and os.name!='nt' and (info.st_mode & 0o077 or (folder/'manifest.json').stat().st_mode & 0o077):
            raise ValueError('Unsafe artifact permissions')
        if not stat.S_ISREG(info.st_mode) or info.st_size != item['zip_size']:
            raise ValueError('Missing ZIP or size mismatch')
        result['reasons'] = [_reason('verification_required', 'Wymagana pełna weryfikacja integralności i aktualności.')]
        return result, item, len(raw)
    except Exception as exc:
        if _unreadable(exc):
            result.update(state='BLOCKED', verification_required=True,
                          reasons=[_reason('metadata_unavailable', 'Nie można wiarygodnie odczytać metadanych paczki.')])
        else:
            result.update(state='INVALID', verification_required=False,
                          reasons=[_reason('invalid_artifact', 'Brak, niepoprawny lub niebezpieczny manifest/ZIP albo niezgodny rozmiar.')])
        return result, None, MAX_MANIFEST


def list_packages(*, portal=None, state=None, offer_id=None, offset=0, limit=50, domain='domestic', subject_kind=None, subject_id=None):
    if domain not in {'domestic','foreign'}: raise CatalogError('Nieznana domena paczki.')
    if subject_kind not in {None,'foreign_offer','cyprus_development'} or subject_id is not None and (type(subject_id) is not int or subject_id<=0):
        raise CatalogError('Nieprawidłowy podmiot.')
    if domain=='domestic' and (subject_kind is not None or subject_id is not None): raise CatalogError('Nieprawidłowy filtr domeny.')
    if domain=='foreign' and portal is not None and portal not in {'domiporta','tabelaofert'}: raise CatalogError('Nieprawidłowy portal.')
    if portal is not None and portal not in preparation.PORTALS: raise CatalogError('Nieprawidłowy portal.')
    if state is not None and state not in STATES: raise CatalogError('Nieprawidłowy stan.')
    if offer_id is not None and (type(offer_id) is not int or offer_id<=0): raise CatalogError('Nieprawidłowe ID oferty.')
    if type(offset) is not int or type(limit) is not int or not 0<=offset<=MAX_SCAN or not 1<=limit<=100:
        raise CatalogError('Nieprawidłowa strona listy.')
    _, base = _root(domain)
    entries, scanned, used, truncated = [], 0, 0, False
    if base.exists():
        try:
            if domain == 'domestic':
                from .domestic_storage import entries as stored_entries, LookupLimit
                selected = {}
                try:
                    for package_id, folder in stored_entries(base):
                        previous = selected.get(package_id)
                        if previous is not None and previous != base/package_id and folder != base/package_id:
                            raise CatalogError('Ambiguous domestic package location',503)
                        if previous is None or folder != base/package_id:
                            selected[package_id] = folder
                except LookupLimit:
                    truncated=True  # listing may be partial; verification may not
                for package_id, folder in selected.items():
                    if scanned>=MAX_SCAN or used>=MAX_METADATA:
                        truncated=True; break
                    scanned+=1
                    row, _, size = _metadata(base, package_id, domain, folder=folder)
                    entries.append(row); used+=size
            else:
                with os.scandir(base) as stream:
                    for entry in stream:
                        if scanned>=MAX_SCAN or used>=MAX_METADATA:
                            truncated=True; break
                        scanned+=1
                        if entry.name.startswith('.') or not ID.fullmatch(entry.name): continue
                        row, item, size = _metadata(base, entry.name, domain)
                        from .foreign_batch import presentation
                        row = presentation(base, row, item)
                        entries.append(row); used+=size
        except OSError:
            raise CatalogError('Nie można wiarygodnie odczytać magazynu.', 503)
    # Only a warning: a newer artifact need not have a different fingerprint.
    newest={}
    def key_for(row):
        subject=row.get('subject',{})
        return (subject.get('kind'),subject.get('id'),row['portal'],row['action']) if domain=='foreign' else (row['offer_id'],row['portal'],row['action'])
    for row in entries:
        if row['prepared_at'] is None: continue
        key=key_for(row)
        rank=(_date(row['prepared_at']),row['package_id'])
        if key not in newest or rank>newest[key][0]: newest[key]=(rank,row['package_id'])
    for row in entries:
        key=key_for(row)
        if key in newest and _date(row['prepared_at'])<newest[key][0][0]:
            row['warnings'].append(_reason('newer_package', 'Istnieje nowsza paczka tej oferty, portalu i akcji.'))
            row['newer_package_id']=newest[key][1]
    entries.sort(key=lambda row: (_date(row['prepared_at']) if row['prepared_at'] else datetime.min.replace(tzinfo=timezone.utc),row['package_id']),reverse=True)
    filtered=[r for r in entries if (portal is None or r['portal']==portal) and (state is None or r['state']==state)
              and (offer_id is None or r['offer_id']==offer_id)
              and (subject_kind is None or r.get('subject',{}).get('kind')==subject_kind)
              and (subject_id is None or r.get('subject',{}).get('id')==subject_id)]
    return {'items':filtered[offset:offset+limit], 'total':len(filtered), 'offset':offset,'limit':limit,
            'scan_truncated':truncated,'scanned':scanned,'metadata_only':True,
            'notice':'Lista jest lekka. READY/STALE wymagają jawnej weryfikacji; wynik dotyczy chwili sprawdzenia.'}


def package_details(package_id, *, domain='domestic'):
    if not isinstance(package_id,str) or not ID.fullmatch(package_id): raise CatalogError('Nieprawidłowe ID paczki.')
    _, base = _root(domain)
    if not _package_exists(base, package_id, domain): raise CatalogError('Paczka nie istnieje.',404)
    if domain == 'domestic':
        from .domestic_sets import presentation, locked
        with locked():
            return presentation(base, package_id)
    return _metadata(base, package_id, domain)[0]


@performance.measured('zip_integrity')
def _zip_integrity(path, base, item):
    limits.check('zip_integrity')
    with _open(path, base) as stream:
        digest=hashlib.sha256(); size=0
        while True:
            limits.check('zip_digest')
            chunk = stream.read(1024*1024)
            if not chunk:break
            size+=len(chunk)
            performance.count('zip_digest_bytes', len(chunk))
            if size>MAX_ZIP: raise ValueError('ZIP limit exceeded')
            digest.update(chunk)
        limits.check('zip_directory')
        if size!=item['zip_size'] or digest.hexdigest()!=item['zip_sha256']: raise ValueError('ZIP digest mismatch')
        # Bound central-directory parsing before ZipFile allocates entry objects.
        stream.seek(max(0,size-65557))
        tail=stream.read(65557)
        pos=tail.rfind(b'PK\x05\x06')
        if pos<0 or len(tail)-pos<22: raise ValueError('Missing ZIP end record')
        _,disk,central_disk,disk_count,count,central_size,central_offset,comment=struct.unpack_from('<4s4H2LH',tail,pos)
        end_position=max(0,size-65557)+pos
        if (disk or central_disk or disk_count!=count or not 0<count<=MAX_ZIP_ENTRIES
                or central_size>4*1024*1024 or central_offset+central_size>end_position
                or pos+22+comment!=len(tail)):
            raise ValueError('Unsupported or oversized central directory')
        stream.seek(0)
        with zipfile.ZipFile(stream) as archive:
            info=archive.infolist()
            if not info or len(info)>MAX_ZIP_ENTRIES or sum(i.file_size for i in info)>MAX_UNPACKED:
                raise ValueError('Archive limits exceeded')
            for entry in info:
                limits.check('zip_entry')
                if entry.flag_bits & 1 or entry.file_size>MAX_ENTRY: raise ValueError('Unsupported entry')
                total=0
                with archive.open(entry) as content:
                    while True:
                        limits.check('zip_content')
                        chunk = content.read(1024*1024)
                        if not chunk:break
                        total+=len(chunk)
                        performance.count('zip_decoded_bytes', len(chunk))
                        if total>MAX_ENTRY: raise ValueError('Decompression limit exceeded')
            if item.get('schema_version')==2:
                from .foreign_packages import validate_xml_archive
                validate_xml_archive(archive,item)


def _input_reader():
    consumed=[0]
    @performance.measured('input_file_read')
    def read(root,path):
        limits.check('input_read')
        if not path.exists() and not _link(path): return None
        with _open(path,root) as stream:
            body=stream.read(MAX_INPUT_FILE+1)
        limits.check('input_read')
        consumed[0]+=len(body)
        performance.count('input_bytes', len(body))
        if len(body)>MAX_INPUT_FILE or consumed[0]>MAX_INPUT_TOTAL: raise preparation.InputLimitError('Input budget exceeded')
        return body
    return read


def _verify_package(package_id, *, settings=None, refresh_dictionaries=False, domain='domestic'):
    limits.check('verify_package')
    if domain=='foreign':
        from .foreign_packages import verify_package as verify_foreign
        with performance.stage('foreign_verification'):
            return verify_foreign(package_id,settings=settings)
    if domain!='domestic': raise CatalogError('Nieznana domena paczki.')
    if not isinstance(package_id,str) or not ID.fullmatch(package_id): raise CatalogError('Nieprawidłowe ID paczki.')
    root,base=_root()
    if not _package_exists(base, package_id, domain): raise CatalogError('Paczka nie istnieje.',404)
    result,item,_=_metadata(base,package_id)
    result['checked_at']=datetime.now(timezone.utc).isoformat()
    if item is None: return result
    reasons={'INVALID':[],'BLOCKED':[],'STALE':[]}
    def add(state,code,message): reasons[state].append(_reason(code,message))
    try:
        _zip_integrity(package_folder(base, package_id)/item['zip_name'],base,item)
    except Exception as exc:
        if _unreadable(exc): add('BLOCKED','zip_unavailable','Nie można wiarygodnie odczytać ZIP.')
        else: add('INVALID','zip_integrity','ZIP jest uszkodzony, niezgodny z hashem lub przekracza limit bezpiecznej kontroli.')
    try:
        offer,*_=preparation._records(root,item['offer_id'])
        preparation._validate(offer,item['portal'],item['action'],root=root)
    except preparation.PreparationError:
        add('BLOCKED','business_conditions','Oferta, lokalizacja lub aktywny agent nie istnieje albo aktualne warunki biznesowe nie dopuszczają tej akcji.')
    except Exception:
        add('BLOCKED','data_unavailable','Nie można wiarygodnie odczytać aktualnych danych oferty.')
    try:
        if refresh_dictionaries:
            dictionaries.dictionary_inputs(item['portal'])
        current_dict=dictionaries.cached_dictionary_context(item['portal'])
        if current_dict is None:
            add('BLOCKED','dictionary_context_unknown','Brak świeżego, kompletnego kontekstu słowników. Ponów kontrolę z odświeżeniem słowników.')
            # Still diagnose changes to offer/media against the captured dictionary
            # context, but never permit READY on the basis of these old responses.
            current_dict=item['generation_context']['dictionaries']
        context=preparation.generation_context(root,item['portal'],item['action'],settings,current_dict,
                                             input_projection=item['generation_context'].get('input_projection'))
        if context!=item['generation_context']:
            add('STALE','generation_context_changed','Zmienił się generator, jego środowisko, słowniki lub metadane generowania.')
        first=preparation._state(root,item['offer_id'],context,file_reader=_input_reader(),max_entries=MAX_INPUT_ENTRIES)[0]
        second=preparation._state(root,item['offer_id'],context,file_reader=_input_reader(),max_entries=MAX_INPUT_ENTRIES)[0]
        if first!=second:
            add('BLOCKED','inputs_unstable','Dane zmieniały się podczas weryfikacji; ponów sprawdzenie.')
        elif first!=item['input_fingerprint']:
            add('STALE','input_fingerprint_changed','Fingerprint bieżących rekordów, opisów, zdjęć lub kontekstu różni się od paczki.')
        # Re-read metadata and ZIP after data checks, preventing a concurrent
        # replacement from being silently accepted as the checked artifact.
        _,current_item,_=_metadata(base,package_id)
        if current_item!=item:
            add('INVALID','artifact_changed','Artefakt zmienił się podczas kontroli.')
        else:
            try:
                _zip_integrity(package_folder(base, package_id)/item['zip_name'],base,item)
            except Exception as exc:
                if _unreadable(exc): add('BLOCKED','zip_unavailable','Nie można ponownie odczytać ZIP.')
                else: add('INVALID','artifact_changed','Integralność ZIP zmieniła się podczas kontroli.')
    except GalleryError:
        add('BLOCKED','ambiguous_gallery','Kilka plików ma ten sam indeks zdjęcia; galeria wymaga rozstrzygnięcia.')
    except Exception:
        add('BLOCKED','verification_unavailable','Nie można wiarygodnie sprawdzić aktualności lub przekroczono limit odczytu.')
    result['reasons']=[r for state in ('INVALID','BLOCKED','STALE') for r in reasons[state]]
    result['state']=next((state for state in ('INVALID','BLOCKED','STALE') if reasons[state]),'READY')
    result['verification_required']=False
    result['transport_eligible']=result['state']=='READY'
    if item['portal']=='domiporta':
        result['warnings'].append(_reason('dictionary_cache_window',
            'Słowniki porównano w ramach cache do 6 godzin; nie jest to potwierdzenie najnowszej wersji zdalnej.'))
    result['notice']='Diagnostyka na chwilę kontroli; nie jest zgodą na transport ani potwierdzeniem publikacji.'
    return result


def verify_package(package_id, *, settings=None, refresh_dictionaries=False, domain='domestic', allow_retired=False):
    if domain != 'domestic':
        return _verify_package(package_id, settings=settings,
                               refresh_dictionaries=refresh_dictionaries, domain=domain)
    if not isinstance(package_id, str) or not ID.fullmatch(package_id):
        raise CatalogError('Nieprawidłowe ID paczki.')
    from . import domestic_sets as sets
    if refresh_dictionaries:
        _, base = _root()
        _, item, _ = _metadata(base, package_id)
        if item is not None:
            dictionaries.dictionary_inputs(item['portal'])
    with sets.locked():
        _, base = _root()
        from .domestic_storage import lookup_scope
        with lookup_scope(base):
            _, item, _ = _metadata(base, package_id)
            if item is not None and not allow_retired and not sets.is_current(base, item):
                result = _metadata(base, package_id)[0]
                result.update(state='STALE', checked_at=datetime.now(timezone.utc).isoformat(),
                              reasons=[_reason('superseded_set', 'Paczka nie należy do aktualnego zestawu.')],
                              verification_required=False, transport_eligible=False)
            else:
                result = _verify_package(package_id, settings=settings)
            try:
                limits.check('save_verification')
                sets.save_verification(base, package_id, result)
            except (OSError, ValueError):
                # Corrupt/linked artifacts must remain diagnosable without writing
                # through an unsafe path. A valid artifact is fail-closed on I/O.
                if item is not None:
                    result.update(state='BLOCKED', transport_eligible=False,
                                  reasons=[_reason('verification_save_failed', 'Nie zapisano wyniku kontroli.')])
            return result
