"""Current domestic sets. Immutable artifacts, one atomic pointer, no startup I/O.

Artifacts are published only in structured directories. SSH receipts supply
their resolved location; manifests and ZIP bytes remain unchanged.
An issued handoff has no release message: pins deliberately never expire.
"""
from contextlib import contextmanager, closing
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import sqlite3
import stat
import tempfile
import uuid

from modules.core import storage_paths
from . import domestic_dictionaries as dictionaries
from .input_consistency import input_lock
from . import domestic_storage as storage
from . import domestic_batch_limits as limits
from . import domestic_batch_timing as timing
from . import export_performance as performance

BASE_PORTALS = ('no', 'domiporta', 'tabelaofert')
PORTALS = BASE_PORTALS + ('gruntguru',)
CHECK_FILE = '.verification.json'
PIN_FILE = '.handoff-pin.json'


@contextmanager
def locked():
    # Same order as export_attempts.transaction; both locks are reentrant.
    with performance.lock_context(limits.locked(dictionaries._lock), 'dictionary_lock'), input_lock():
        yield


def _catalog():
    from . import domestic_package_catalog
    return domestic_package_catalog


def _selection(offer_id, action):
    if type(offer_id) is not int or not 0 < offer_id <= 2**63-1 or action not in ('add', 'delete'):
        raise _catalog().CatalogError('Nieprawidłowa oferta lub operacja zestawu.')


def is_plot(value):
    return str(value or '').strip().lower() in {'działka', 'dzialka'}


def portals_for_offer(root, offer_id, action):
    """GruntGuru publishes plots; a reclassified published plot can withdraw."""
    with closing(sqlite3.connect((root/'databases/IDB.db').resolve().as_uri()+'?mode=ro', uri=True, **limits.sqlite_options())) as conn:
        limits.database(root/'databases/IDB.db', conn)
        row = conn.execute('SELECT Typ_nieruchomosci FROM EstateData WHERE ID=?', (offer_id,)).fetchone()
        if row is None:
            raise _catalog().CatalogError('Oferta nie istnieje.', 404)
        published = False
        if action == 'delete' and conn.execute("SELECT 1 FROM sqlite_master WHERE name='offer_portal_sync'").fetchone():
            state = conn.execute("SELECT is_published FROM offer_portal_sync WHERE offer_id=? AND portal_key='gruntguru'", (offer_id,)).fetchone()
            published = bool(state and state[0])
    return PORTALS if is_plot(row[0]) or published else BASE_PORTALS


def _safe(path, base):
    storage.safe(path, base)


def _mkdir(path, base):
    current = base
    for part in path.relative_to(base).parts:
        current = current / part
        _safe(current, base)
        existed = current.exists()
        current.mkdir(mode=0o700, exist_ok=True)
        if os.name != 'nt' and current.stat().st_mode & 0o077:
            raise ValueError('Set storage must be private')
        if not existed and os.name != 'nt':
            descriptor = os.open(current.parent, os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0))
            try:
                os.fsync(descriptor)
            finally:
                os.close(descriptor)


def _json_read(path, base):
    with _catalog()._open(path, base) as stream:
        body = stream.read(65537)
    if len(body) > 65536:
        raise ValueError('Set metadata limit exceeded')
    def unique(pairs):
        result = {}
        for key, value in pairs:
            if key in result:
                raise ValueError('Duplicate metadata key')
            result[key] = value
        return result
    return json.loads(body, object_pairs_hook=unique)


def _atomic_json(path, value, base):
    _safe(path, base)
    fd, name = tempfile.mkstemp(prefix='.' + path.name, suffix='.tmp', dir=path.parent)
    try:
        with os.fdopen(fd, 'wb') as stream:
            stream.write(json.dumps(value, ensure_ascii=False, sort_keys=True).encode('utf8'))
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(name, path)
        if os.name != 'nt':
            descriptor = os.open(path.parent, os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0))
            try:
                os.fsync(descriptor)
            finally:
                os.close(descriptor)
    finally:
        if os.path.exists(name):
            os.unlink(name)


def current(base, offer_id, action):
    _selection(offer_id, action)
    path = base / str(offer_id) / action / 'current.json'
    _safe(path, base)
    if not path.exists():
        return None
    value = _json_read(path, base)
    if (not isinstance(value, dict)
            or set(value) != {'schema_version', 'generation_id', 'offer_id', 'action', 'packages', 'prepared_at'}
            or type(value['schema_version']) is not int or value['schema_version'] != 1
            or type(value['offer_id']) is not int or value['offer_id'] != offer_id or value['action'] != action
            or not isinstance(value['generation_id'], str) or not _catalog().ID.fullmatch(value['generation_id'])
            or not isinstance(value['packages'], dict) or set(value['packages']) not in (set(BASE_PORTALS), set(PORTALS))
            or any(not isinstance(i, str) or not _catalog().ID.fullmatch(i) for i in value['packages'].values())
            or len(set(value['packages'].values())) != len(value['packages'])):
        raise ValueError('Invalid current-set pointer')
    _catalog()._date(value['prepared_at'])
    return value


def nested(base, item):
    return storage.structured(base, item)


def is_current(base, item):
    pointer = current(base, item['offer_id'], item['action'])
    if pointer is not None:
        return pointer['packages'].get(item['portal']) == item['package_id']
    # Unmanaged old flat artifacts remain compatible; uncommitted new ones do not.
    path = nested(base, item)
    _safe(path, base)
    if not path.exists():
        return True  # old, flat-only package
    try:
        marker = _json_read(path/storage.STANDALONE, base)
        return marker == {'package_id': item['package_id']}
    except (OSError, ValueError):
        return False  # staged/crashed set publication is never a standalone


def _manifest_hash(base, package_id, *, folder=None):
    try:
        if folder is None:
            folder = storage.folder(base, package_id)
        else:
            storage.safe(folder, base)
        with _catalog()._open(folder/'manifest.json', base) as stream:
            raw = stream.read(65537)
        return hashlib.sha256(raw).hexdigest() if len(raw) <= 65536 else None
    except (OSError, ValueError):
        return None


def save_verification(base, package_id, result):
    folder = storage.folder(base, package_id)
    _safe(folder, base)
    if not folder.is_dir():
        return
    saved = {key: result[key] for key in ('state', 'checked_at', 'reasons', 'warnings', 'verification_required')}
    _atomic_json(folder/CHECK_FILE, {'schema_version': 1, 'package_id': package_id,
                 'manifest_sha256': _manifest_hash(base, package_id), 'result': saved}, base)


def presentation(base, package_id, *, locations=None):
    result, item, _ = _catalog()._metadata(base, package_id, locations=locations)
    try:
        folder = storage.folder(base, package_id, locations=locations)
        check_path = folder/CHECK_FILE
        # INT-014 stored control files in its old compatibility view. Read that
        # last result only if the canonical store has no newer result.
        if not check_path.exists() and folder != base/package_id:
            legacy = base/package_id/CHECK_FILE
            _safe(legacy, base)
            check_path = legacy
        saved = _json_read(check_path, base)
        valid = (isinstance(saved, dict) and saved.get('schema_version') == 1
                 and saved.get('package_id') == package_id
                 and saved.get('manifest_sha256') == _manifest_hash(base, package_id,
                      folder=folder if locations is not None else None)
                 and isinstance(saved.get('result'), dict)
                 and set(saved['result']) == {'state', 'checked_at', 'reasons', 'warnings', 'verification_required'}
                 and type(saved['result'].get('verification_required')) is bool
                 and all(isinstance(saved['result'].get(key), list) for key in ('reasons', 'warnings'))
                 and all(isinstance(entry, dict) and isinstance(entry.get('code'), str)
                         and isinstance(entry.get('message'), str)
                         for key in ('reasons', 'warnings') for entry in saved['result'][key])
                 and saved['result'].get('state') in _catalog().STATES)
        if valid:
            _catalog()._date(saved['result']['checked_at'])
            if item is not None:
                result.update(saved['result'])
            else:
                result['checked_at'] = saved['result']['checked_at']
    except FileNotFoundError:
        valid = False
    except (OSError, ValueError, KeyError, TypeError):
        valid = False
    if item is not None and not valid:
        result.update(state='UNVERIFIED', checked_at=None,
                      verification_required=True, reasons=[{'code': 'verification_required',
                      'message': 'Zestaw nie został jeszcze zweryfikowany.'}])
    if item is not None and not is_current(base, item):
        result.update(state='STALE', reasons=[{'code': 'superseded_set',
                      'message': 'Paczka nie należy do aktualnego zestawu.'}])
    # A persisted READY is a historical check, never permission to send.
    result['transport_eligible'] = False
    result['notice'] = 'Ostatni zapisany wynik. Przekazanie do wysyłki wymaga nowej kontroli.'
    return result


def pin(base, package_id):
    """Caller holds locked()/input_lock. Never expire an un-released reader."""
    folder = storage.folder(base, package_id)
    _safe(folder, base)
    if not folder.is_dir():
        raise ValueError('Handoff artifact unavailable')
    marker = folder/PIN_FILE
    _safe(marker, base)
    if not marker.exists():
        _atomic_json(marker, {'schema_version': 1, 'package_id': package_id,
                     'issued_at': datetime.now(timezone.utc).isoformat()}, base)


def _row(base, pointer, checks=None, *, locations=None):
    portals = [portal for portal in PORTALS if portal in pointer['packages']]
    packages = [presentation(base, pointer['packages'][portal], locations=locations) for portal in portals]
    # A corrupt flat manifest cannot relabel another portal/offer in a set.
    for portal, row in zip(portals, packages):
        if checks and row['package_id'] in checks:
            # Return this operation's diagnostics even if disk failure prevented
            # persisting them; never replace a failed fresh check with old READY.
            checked = checks[row['package_id']]
            row.update({key: checked[key] for key in
                        ('state', 'checked_at', 'reasons', 'warnings', 'verification_required')})
        if row['offer_id'] is not None and (row['offer_id'], row['portal'], row['action']) != (pointer['offer_id'], portal, pointer['action']):
            row.update(state='INVALID', reasons=[{'code': 'set_binding', 'message': 'Niezgodna paczka zestawu.'}])
        row.update(offer_id=pointer['offer_id'], portal=portal, action=pointer['action'])
    states = {row['state'] for row in packages}
    state = next((s for s in ('INVALID', 'BLOCKED', 'STALE', 'UNVERIFIED') if s in states), 'READY')
    return {**pointer, 'state': state, 'items': packages, 'transport_eligible': False}


def list_sets(*, offer_id=None, action=None, state=None, offset=0, limit=50, all_items=False):
    catalog = _catalog()
    if offer_id is not None:
        _selection(offer_id, action or 'add')
    if (state not in catalog.STATES | {'UNVERIFIED', None} or action not in (None, 'add', 'delete')
            or type(offset) is not int or type(limit) is not int or not 0 <= offset <= catalog.MAX_SCAN or not 1 <= limit <= 100
            or type(all_items) is not bool or all_items and offset != 0):
        raise catalog.CatalogError('Nieprawidłowe filtry zestawów.')
    _, base = catalog._root()
    pointers, rows, scanned, truncated = [], [], 0, False
    if base.exists():
        with locked():
            for folder in base.iterdir():
                if not folder.name.isascii() or not folder.name.isdecimal() or len(folder.name) > 19 or not 0 < int(folder.name) <= 2**63-1:
                    continue
                if str(int(folder.name)) != folder.name:
                    continue
                scanned += 1
                if scanned > catalog.MAX_SCAN:
                    truncated = True
                    break
                if offer_id is not None and int(folder.name) != offer_id:
                    continue
                _safe(folder, base)
                if not folder.is_dir():
                    continue
                for operation in (action,) if action else ('add', 'delete'):
                    pointer = current(base, int(folder.name), operation)
                    if pointer:
                        pointers.append(pointer)
            pointers.sort(key=lambda row: (row['prepared_at'], row['generation_id']), reverse=True)
            selected = pointers if state or all_items else pointers[offset:offset+limit]
            if selected:
                locations = storage.location_index(base)
                rows = [_row(base, pointer, locations=locations) for pointer in selected]
            if state:
                rows = [row for row in rows if row['state'] == state]
    total = len(rows) if state else len(pointers)
    return {'items': rows if all_items else (rows[offset:offset+limit] if state else rows), 'total': total, 'offset': offset, 'limit': limit,
            'scan_truncated': truncated, 'notice': 'Tylko aktualne kompletne zestawy. READY jest ostatnim wynikiem kontroli; przed wysyłką paczka będzie sprawdzona ponownie.'}


@timing.measured('prepare_set', action_arg=1)
def prepare_set(offer_id, action, *, settings=None, _guard=None, _bounded_inputs=False):
    limits.check('prepare_set')
    from . import domestic_packages as prep
    _selection(offer_id, action)
    root = storage_paths.data_dir()
    if root is None or not root.is_dir():
        raise prep.PreparationError('generation_error', 'Brak zewnętrznego InvestmentData.', 503)
    root = root.resolve()
    with locked():
        blocked = _guard() if _guard else None
        if blocked:
            return {'offer_id': offer_id, 'action': action, 'portal_results': {},
                    'replaced': False, 'outcome': 'qualification_changed', 'block_reason': blocked}
        # Serialize initial directory provisioning as well as pointer access.
        # In particular, concurrent first runs must not resolve half-created
        # directory chains on Windows or inspect each other's provisioning.
        base = prep._private_root(root)
        before = current(base, offer_id, action)
        portals = portals_for_offer(root, offer_id, action)
    if _bounded_inputs:
        # Only the bulk caller opts in. Reject oversized media before snapshots,
        # artifact staging or generation; copies remain bounded against races.
        try:
            prep._limited_state(root, offer_id, {})
        except prep.InputLimitError as exc:
            raise prep.PreparationError('input_limit', 'Przekroczono limit pliku, łącznego rozmiaru mediów lub liczby wpisów katalogu. Zmniejsz wejścia i uruchom ponownie.', 413) from exc
    results = {}
    with tempfile.TemporaryDirectory(prefix='.set-', dir=base) as directory:
        staging = Path(directory)
        for portal in portals:
            limits.check('prepare_portal')
            try:
                options = {'_bounded_inputs': True} if _bounded_inputs else {}
                item = prep.prepare_package(offer_id, portal, action, settings=settings, _destination=staging, **options)
                results[portal] = {'success': True, **item}
            except prep.PreparationError as exc:
                results[portal] = {'success': False, 'outcome': exc.outcome, 'error': str(exc)}
            except Exception:
                results[portal] = {'success': False, 'outcome': 'generation_error', 'error': 'Nie udało się przygotować paczki portalu.'}
        response = {'offer_id': offer_id, 'action': action, 'portal_results': results, 'replaced': False, 'outcome': 'not_replaced'}
        if not all(row['success'] for row in results.values()):
            return response
        try:
            with locked():
                blocked = _guard() if _guard else None
                if blocked:
                    return response | {'outcome': 'qualification_changed', 'block_reason': blocked}
                if current(base, offer_id, action) != before:
                    return response | {'error': 'Inny proces zmienił aktualny zestaw. Przygotowane pliki nie zostały aktywowane.'}
                if portals_for_offer(root, offer_id, action) != portals:
                    return response | {'error': 'Zmienił się zakres portali oferty. Przygotuj kompletny zestaw ponownie.'}
                with timing.stage('preactivation_check', action=action):
                    for portal, result in results.items():
                        limits.check('validate_staged_portal')
                        _, item, _ = _catalog()._metadata(staging, result['package_id'])
                        read_state = prep._limited_state if _bounded_inputs else prep._state
                        if item is None or read_state(root, offer_id, item['generation_context'])[0] != item['input_fingerprint']:
                            return response | {'error': 'Dane zmieniły się podczas przygotowywania zestawu.'}
                        _catalog()._zip_integrity(staging/item['package_id']/item['zip_name'], staging, item)
                # One commit stage: once entered, finish publishing the complete
                # set and its atomic pointer; do not stop halfway through it.
                with timing.stage('activation', action=action):
                    limits.check('activate_set')
                    for portal, result in results.items():
                        _, item, _ = _catalog()._metadata(staging, result['package_id'])
                        target = nested(base, item)
                        _mkdir(target.parent, base)
                        _safe(target, base)
                        prep._publish(staging/item['package_id'], target)
                    parent = base/str(offer_id)/action
                    pointer = {'schema_version': 1, 'offer_id': offer_id, 'action': action,
                               'generation_id': uuid.uuid4().hex, 'prepared_at': datetime.now(timezone.utc).isoformat(),
                               'packages': {portal: row['package_id'] for portal, row in results.items()}}
                    _atomic_json(parent/'current.json', pointer, base)
                    response.update(replaced=True, outcome='prepared', generation_id=pointer['generation_id'])
        except prep.InputLimitError:
            return response | {'outcome': 'input_limit',
                               'error': 'Przekroczono limit wejść przed aktywacją zestawu. Zmniejsz wejścia i uruchom ponownie.'}
        except Exception as exc:
            limits.raise_if_locked(exc)
            try:
                active = current(base, offer_id, action)
                activated = active is not None and active['packages'] == {
                    portal: row['package_id'] for portal, row in results.items()}
            except Exception:
                activated = False
            if not activated:
                return response | {'error': 'Operacja nie aktywowała zestawu. Sprawdź uprawnienia i miejsce na dysku, następnie odśwież listę.'}
            response.update(replaced=True, outcome='prepared', generation_id=active['generation_id'],
                            warning='Komplet aktywowano, ale potwierdzenie trwałości zapisu nie powiodło się. Wymagana kontrola dysku.')
    # Cleanup never turns a successfully activated complete set into a failure.
    try:
        limits.check('cleanup')
        response['cleanup'] = cleanup(offer_id=offer_id, action=action)
    except limits.BatchStop:
        response['cleanup'] = {'warning': 'Czyszczenie odłożono; kompletny zestaw został aktywowany.'}
    except Exception:
        response['cleanup'] = {'warning': 'Czyszczenie odłożono; aktualny zestaw jest kompletny.'}
    return response


def verify_set(offer_id, action, *, generation_id=None, settings=None, refresh_dictionaries=True):
    _selection(offer_id, action)
    if type(refresh_dictionaries) is not bool:
        raise _catalog().CatalogError('Nieprawidłowe odświeżenie słowników.')
    if refresh_dictionaries:
        dictionaries.dictionary_inputs('domiporta')
    _, base = _catalog()._root()
    with locked():
        pointer = current(base, offer_id, action)
        if pointer is None:
            raise _catalog().CatalogError('Brak aktualnego zestawu.', 404)
        if generation_id is not None and generation_id != pointer['generation_id']:
            raise _catalog().CatalogError('Aktualny zestaw zmienił się. Odśwież widok.', 409)
        checks = {}
        for portal, package_id in pointer['packages'].items():
            limits.check('verify_portal')
            try:
                with timing.stage('verify_portal', action=action, portal=portal):
                    result = _catalog().verify_package(package_id, settings=settings)
            except Exception:
                result = _catalog()._empty(package_id)
                result.update(checked_at=datetime.now(timezone.utc).isoformat(),
                              reasons=[{'code': 'verification_unavailable', 'message': 'Nie można teraz zweryfikować paczki.'}])
                try:
                    save_verification(base, package_id, result)
                except Exception:
                    result['reasons'].append({'code': 'verification_save_failed',
                                             'message': 'Nie zapisano wyniku kontroli.'})
            checks[package_id] = result
        group = _row(base, pointer, checks)
        save_errors = [package_id for package_id, result in checks.items()
                       if any(r['code'] == 'verification_save_failed' for r in result['reasons'])]
        if save_errors:
            group['save_errors'] = save_errors
        return group


def _referenced(package_id):
    """Any durable attempt is retained, even if its reader pin was lost."""
    path = storage_paths.idb_db_path()
    if not path.exists():
        return False
    with closing(sqlite3.connect(path.resolve().as_uri()+'?mode=ro', uri=True, **limits.sqlite_options())) as conn:
        limits.database(path, conn)
        if not conn.execute("SELECT 1 FROM sqlite_master WHERE name='offer_portal_sync_events'").fetchone():
            return False
        for raw, in conn.execute("SELECT payload_json FROM offer_portal_sync_events WHERE event_type='export_attempt_v1'"):
            value = json.loads(raw)
            if value['binding']['package_id'] == package_id:
                return True
    return False


def cleanup(*, offer_id, action):
    """Only managed, retired, never-issued artifacts; no recursive deletion."""
    _selection(offer_id, action)
    _, base = _catalog()._root()
    result = {'removed': [], 'retained': [], 'errors': []}
    with locked():
        pointer = current(base, offer_id, action)
        active = set(pointer['packages'].values()) if pointer else set()
        scanned = 0
        for portal in PORTALS:
            parent = base/str(offer_id)/action/portal
            _safe(parent, base)
            if not parent.exists():
                continue
            for folder in parent.iterdir():
                scanned += 1
                if scanned > _catalog().MAX_SCAN:
                    result['errors'].append('Osiągnięto limit czyszczenia.')
                    return result
                package_id = folder.name
                if not _catalog().ID.fullmatch(package_id) or package_id in active:
                    continue
                try:
                    _safe(folder, base)
                    alias = base/package_id
                    _safe(alias, base)
                    if (_catalog()._link(alias) or alias.exists()
                            or _catalog()._link(folder/PIN_FILE) or (folder/PIN_FILE).exists()
                            or _referenced(package_id)):
                        result['retained'].append(package_id)
                        continue
                    _, item, _ = _catalog()._metadata(base, package_id)
                    if item is None or nested(base, item) != folder:
                        raise ValueError('Unrecognized artifact; retain')
                    allowed = {'manifest.json', item['zip_name'], CHECK_FILE, storage.STANDALONE}
                    files = []
                    for directory in (folder,):
                        for path in directory.iterdir():
                            _safe(path, base)
                            if path.name not in allowed or not stat.S_ISREG(path.lstat().st_mode):
                                raise ValueError('Unrecognized cleanup entry')
                            files.append(path)
                    # Paths have been resolved, constrained to base and checked above.
                    for path in files:
                        path.unlink()
                    folder.rmdir()
                    result['removed'].append(package_id)
                except Exception:
                    result['errors'].append(package_id)
    return result
