"""One domestic artifact location; legacy files are read, never migrated.

No registry, persistent cache or startup I/O. Locked operations reuse a bounded
location index and recheck it before success; SSH receipts carry relative paths.
"""
from . import domestic_batch_limits as limits
from . import export_performance as performance
from .input_consistency import ConsistencyError
from contextlib import contextmanager
from contextvars import ContextVar
import os
import threading

_lookup = ContextVar('domestic_locked_lookup', default=None)


class LookupChanged(ConsistencyError):
    pass

LAYOUT = 'offer-operation-portal-v1'
STANDALONE = '.standalone-ready.json'


class LookupLimit(ValueError):
    pass


def _catalog():
    from . import domestic_package_catalog
    return domestic_package_catalog


def safe(path, base):
    catalog = _catalog()
    catalog._safe(path, base)
    current = base
    for part in path.absolute().relative_to(base.absolute()).parts:
        current = current / part
        if catalog._link(current):
            raise ValueError('Linked domestic storage')


def structured(base, item):
    return base/str(item['offer_id'])/item['action']/item['portal']/item['package_id']


def entries(base):
    """Bound every directory traversal; caller bounds metadata reads as well."""
    performance.count('storage_scans')
    catalog = _catalog()
    if not base.exists():
        return
    seen = 0
    for offer in base.iterdir():
        limits.check('artifact_lookup')
        seen += 1
        if seen > catalog.MAX_SCAN * 10:
            raise LookupLimit('Domestic lookup budget exceeded')
        if catalog.ID.fullmatch(offer.name):
            yield offer.name, offer  # immutable legacy view, including bad links
            continue
        if (not offer.name.isascii() or not offer.name.isdecimal()
                or len(offer.name) > 19 or not 0 < int(offer.name) <= 2**63-1
                or str(int(offer.name)) != offer.name):
            continue
        safe(offer, base)
        if not offer.is_dir():
            continue
        for action in ('add', 'delete'):
            for portal in ('no', 'domiporta', 'tabelaofert', 'gruntguru'):
                parent = offer/action/portal
                safe(parent, base)
                if not parent.exists():
                    continue
                for artifact in parent.iterdir():
                    limits.check('artifact_lookup')
                    seen += 1
                    if seen > catalog.MAX_SCAN * 10:
                        raise LookupLimit('Domestic lookup budget exceeded')
                    if catalog.ID.fullmatch(artifact.name):
                        yield artifact.name, artifact


@performance.measured('storage_index')
def location_index(base):
    """One complete lookup for a locked listing; never retain between requests.

    Keep all structured matches so ambiguity remains a per-package failure,
    including when an unrelated package has a duplicate UUID.
    """
    locations = {}
    for package_id, path in entries(base):
        if path != base/package_id:
            locations.setdefault(package_id, []).append(path)
    return locations


@contextmanager
def lookup_scope(base):
    """Only reuse locations inside input_lock; rescan before returning success.

    Publication, cleanup and pointer writes use the same lock. Safe path/file
    opens remain live checks. A second full scan also rejects an out-of-protocol
    relocation/duplicate introduced during verification. Never cache READY.
    """
    from .input_consistency import _held
    held = _held.get()
    owner = (os.getpid(), threading.get_ident())
    if held is None or held['owner'] != owner:
        raise ConsistencyError('Location reuse requires input_lock')
    previous = _lookup.get()
    if previous is not None and previous['base'] == base and previous['owner'] == owner:
        yield
        return
    try:
        locations, error = location_index(base), None
    except (OSError, ValueError) as exc:
        # Preserve per-package INVALID/BLOCKED diagnostics for bad storage.
        locations, error = None, exc
    current = dict(base=base, owner=owner, locations=locations, error=error, used={})
    token = _lookup.set(current)
    try:
        yield
        if current['used']:
            try:
                fresh = location_index(base)
                for package_id, before in current['used'].items():
                    if folder(base, package_id, locations=fresh) != before:
                        raise ValueError('Location changed')
            except (OSError, ValueError) as exc:
                raise LookupChanged('Artifact namespace changed during verification') from exc
    finally:
        _lookup.reset(token)


def folder(base, package_id, *, locations=None):
    catalog = _catalog()
    if not isinstance(package_id, str) or not catalog.ID.fullmatch(package_id):
        raise ValueError('Invalid package ID')
    # A set's private staging area is not a published export store.
    if base.name != 'domestic':
        return base/package_id
    scope = _lookup.get()
    scoped = (locations is None and scope is not None and scope['base'] == base
              and scope['owner'] == (os.getpid(), threading.get_ident()))
    if scoped:
        if scope['error'] is not None:
            raise scope['error']
        locations = scope['locations']
    matches = ([path for name, path in entries(base) if name == package_id and path != base/package_id]
               if locations is None else locations.get(package_id, []))
    if len(matches) > 1:
        raise ValueError('Ambiguous domestic package location')
    result = matches[0] if matches else base/package_id
    safe(result, base)
    if scoped:
        scope['used'][package_id] = result
    return result


def receipt_path(base, package_id):
    path = folder(base, package_id)
    safe(path, base)
    return path.relative_to(base.parent).as_posix()
