"""Preparation-only Segments proposal: emit physical packs directly.

Legacy virtual 128/512 KiB refs remain readable via the bounded whole-200
adapter. No corresponding logical segment files are created. Import is inert.
The enclosing writer still needs a reviewed resource/ownership admission gate.
"""
import gzip
import hashlib
import json
import re
import zlib
from pathlib import Path

PACK_BYTES = 4 * 1024 * 1024
MEMBER_BYTES = 256 * 1024
ZERO = bytes(64 * 1024)

def need(ok, message):
    if not ok:
        raise ValueError(message)

class PackedSegments:
    def __init__(self, target, release, segment_bytes, start_number=0, gate=None):
        need(re.fullmatch('[a-f0-9]{24}', release) is not None, 'Invalid direct-packed release')
        need((segment_bytes, start_number) in ((131072, 0), (524288, 500000)), 'Invalid hot/evidence lane')
        need(callable(gate), 'Reviewed per-write resource/deadline gate is required')
        self.target, self.release, self.cap, self.gate = Path(target), release, segment_bytes, gate
        self.kind = 'hot' if start_number == 0 else 'evidence'
        self.start, self.number = start_number, start_number - 1
        self.members = self.payload_bytes = self.offset = 0
        self.logical_count = self.pack_offset = 0
        self.files, self.physical_files = [], []
        self.stream = self.logical_hash = None
        self.closed = False

    def _write(self, data, logical=False):
        self.gate()
        need(self.stream is not None and self.pack_offset + len(data) <= PACK_BYTES, 'Physical pack bound exceeded')
        need(self.stream.write(data) == len(data), 'Short physical pack write')
        self.pack_offset += len(data)
        if logical:
            self.logical_hash.update(data)

    def _pad(self, size, logical=False):
        while size:
            n = min(size, len(ZERO))
            self._write(ZERO[:n], logical)
            size -= n

    def _finish_pack(self):
        if self.stream is None:
            return
        self._pad(PACK_BYTES - self.pack_offset)
        self.stream.flush()
        self.stream.close()
        self.stream = None
        need(self.path.stat().st_size == PACK_BYTES, 'Physical pack size changed')
        digest = hashlib.sha256()
        with self.path.open('rb') as source:
            for block in iter(lambda: source.read(64 * 1024), b''):
                self.gate()
                digest.update(block)
        self.physical_files.append({'path': str(self.path), 'bytes': PACK_BYTES, 'sha256': digest.hexdigest()})

    def _finish_logical(self):
        if self.logical_hash is None:
            return
        self._pad(self.cap - self.offset, logical=True)
        # Keep legacy len(writer.files) semantics: logical segment count.
        # Only physical_files may enter the deployable static inventory.
        self.files.append({'path': self._logical_path(), 'bytes': self.cap,
                           'sha256': self.logical_hash.hexdigest(), 'published_as_file': False})
        self.logical_hash = None
        if self.pack_offset == PACK_BYTES:
            self._finish_pack()

    def _logical_path(self):
        return '/assets/public-name-data/' + self.release + '/segments/' + f'{self.number:06d}.bin'

    def _new_logical(self):
        self._finish_logical()
        self.number += 1
        need(self.number < (500000 if self.start == 0 else 1000000), 'Logical lane exhausted')
        if self.stream is None:
            ordinal = self.logical_count // (PACK_BYTES // self.cap)
            need(ordinal < 10000, 'Physical pack ordinal exceeds fixed filename layout')
            self.path = self.target / 'packs/direct04m' / (self.kind + '-' + f'{ordinal:04d}.bin')
            self.path.parent.mkdir(parents=True, exist_ok=True)
            self.stream = self.path.open('xb')
            self.pack_offset = 0
        self.offset = 0
        self.logical_hash = hashlib.sha256()
        self.logical_count += 1

    def add(self, value):
        need(not self.closed, 'Direct-packed writer is closed')
        self.gate()
        raw = (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':')) + '\n').encode('utf-8')
        need(0 < len(raw) <= MEMBER_BYTES, 'Inflated member exceeds reader bound')
        packed = gzip.compress(raw, compresslevel=6, mtime=0)
        need(0 < len(packed) <= min(self.cap, MEMBER_BYTES), 'Stored member exceeds logical/member bound')
        if self.logical_hash is None or self.offset + len(packed) > self.cap:
            self._new_logical()
        ref = {'path': self._logical_path(), 'segment_bytes': self.cap, 'offset': self.offset,
               'bytes': len(packed), 'sha256': hashlib.sha256(packed).hexdigest(), 'inflated_bytes': len(raw)}
        self._write(packed, logical=True)
        self.offset += len(packed)
        self.members += 1
        self.payload_bytes += len(packed)
        return ref

    def close(self):
        if not self.closed:
            self._finish_logical()
            self._finish_pack()
            self.closed = True

    def read_member(self, ref):
        """Bounded compiler hook replacing filesystem reads of virtual assets.

        V7's fresh compile_indexes adapter must call this hook; the old compiler
        assumes individual segment files and cannot be used unchanged.
        """
        need(self.closed, 'Compile only after the physical lane is fully closed')
        self.gate()
        match = re.fullmatch('/assets/public-name-data/' + self.release + '/segments/([0-9]{6})[.]bin', ref['path'])
        need(match is not None, 'Compiler reference outside release')
        number = int(match[1])
        ordinal = number - self.start
        need(0 <= ordinal < self.logical_count and ref['segment_bytes'] == self.cap,
             'Compiler logical lane differs')
        for name in ('offset', 'bytes', 'inflated_bytes'):
            need(type(ref[name]) is int, 'Compiler reference is not an integer')
        need(0 <= ref['offset'] < self.cap and 0 < ref['bytes'] <= MEMBER_BYTES and
             ref['offset'] + ref['bytes'] <= self.cap and 0 < ref['inflated_bytes'] <= MEMBER_BYTES,
             'Compiler selected-member budget differs')
        pack_ordinal, slot = divmod(ordinal, PACK_BYTES // self.cap)
        path = self.target / 'packs/direct04m' / (self.kind + '-' + f'{pack_ordinal:04d}.bin')
        need(path.stat().st_size == PACK_BYTES, 'Compiler physical pack changed size')
        with path.open('rb') as source:
            source.seek(slot * self.cap + ref['offset'])
            packed = source.read(ref['bytes'])
        need(len(packed) == ref['bytes'] and hashlib.sha256(packed).hexdigest() == ref['sha256'],
             'Compiler selected member hash differs')
        decoder = zlib.decompressobj(31)
        raw = decoder.decompress(packed, MEMBER_BYTES + 1)
        need(len(raw) == ref['inflated_bytes'] and decoder.eof and not decoder.unused_data and
             not decoder.unconsumed_tail, 'Compiler member CRC/EOF/inflation bound differs')
        return json.loads(raw.decode('utf-8', errors='strict'))

def capacity(retained_static_files, hot_segments, evidence_segments, other_new_static_files):
    """Exact integer geometry from completed counts; never a name-yield estimate."""
    need(all(type(x) is int and x >= 0 for x in (retained_static_files, hot_segments, evidence_segments, other_new_static_files)),
         'Capacity requires measured nonnegative integer counts')
    hot_packs, evidence_packs = (hot_segments + 31) // 32, (evidence_segments + 7) // 8
    total = retained_static_files + hot_packs + evidence_packs + other_new_static_files
    return {'retained_static_files': retained_static_files, 'hot_packs': hot_packs, 'evidence_packs': evidence_packs,
            'other_new_static_files': other_new_static_files, 'total_static_files': total,
            'remaining_file_slots': 20000 - total, 'file_gate_pass': total <= 20000,
            'physical_pack_bytes': PACK_BYTES, 'logical_segment_files_added': 0,
            'current_counts_only_not_50M_capacity': True}
