"""Controlled SSH JSON entry point; OS account is a trusted publisher.

No HTTP endpoint or FTP implementation. SSH authenticates the publisher,
not the truth of a publisher's claim that FTP succeeded.
"""
import contextlib
from datetime import datetime, timezone
import hashlib
import io
import json
import os
from pathlib import Path
import sys
import re
from .integrator import export_performance as performance

OPERATIONS={'create_attempt','start_transport','record_transport_result','acknowledge_attempt','get_attempt'}
MAX_REQUEST=16384
BINDING_KEYS={'package_id','offer_id','portal','action','input_fingerprint','zip_sha256','zip_size','zip_name','manifest_sha256'}


def valid_selection(value):
    return (isinstance(value,dict) and isinstance(value.get('package_id'),str)
        and re.fullmatch(r'[a-f0-9]{32}',value['package_id']) is not None
        and type(value.get('offer_id')) is int and 0<value['offer_id']<=2**63-1
        and isinstance(value.get('portal'),str) and value['portal'] in {'no','domiporta','tabelaofert','gruntguru'}
        and value.get('action') in ('add','delete'))


def valid_binding(value):
    return (valid_selection(value) and set(value)==BINDING_KEYS
        and all(isinstance(value.get(k),str) and re.fullmatch(r'[a-f0-9]{64}',value[k])
                for k in ('input_fingerprint','zip_sha256','manifest_sha256'))
        and type(value.get('zip_size')) is int and 0<value['zip_size']<=128*1024*1024
        and isinstance(value.get('zip_name'),str) and '..' not in value['zip_name']
        and re.fullmatch(r'[A-Za-z0-9_.-]{1,120}\.zip',value['zip_name']) is not None)


@performance.measured('handoff_dispatch')
def dispatch_request(request):
    if isinstance(request,dict) and request.get('operation') == 'list_sync_offers':
        if set(request) != {'operation','offset','limit','categories','portals','snapshot'}:
            return {'view_version':1,'ok':False,'error':'invalid_request'}
        from .integrator.sync_tasks import list_offers, ViewError
        try:
            return list_offers(**{key:request[key] for key in ('offset','limit','categories','portals','snapshot')},settings=os.environ)
        except ViewError as exc:
            return {'view_version':1,'ok':False,'error':exc.code}
        except Exception:
            return {'view_version':1,'ok':False,'error':'queue_unavailable'}
    if isinstance(request,dict) and request.get('operation') == 'list_sync_tasks':
        if set(request) != {'operation','offset','limit'}:
            return {'queue_version':1,'ok':False,'error':'invalid_request'}
        try:
            from .integrator.sync_tasks import list_tasks
            return list_tasks(offset=request['offset'],limit=request['limit'],settings=os.environ)
        except Exception:
            return {'queue_version':1,'ok':False,'error':'queue_unavailable'}
    if isinstance(request,dict) and ('protocol_version' in request or 'domain' in request):
        return dispatch_foreign(request)
    if not isinstance(request,dict) or 'operation' not in request:
        return confirm_package(request)  # unchanged INT-005 request contract
    op=request.get('operation')
    reply={'protocol_version':1,'operation':op if isinstance(op,str) and op in OPERATIONS else None,'ok':False}
    def denied(code):return reply | {'error':code}
    required={'operation','attempt_id'}
    if not isinstance(op,str) or op not in OPERATIONS:
        return denied('invalid_request')
    if op=='create_attempt':required|={'package_id','offer_id','portal','action'}
    elif op!='get_attempt':required.add('binding')
    if op=='record_transport_result':required.add('outcome')
    if (set(request)!=required or not isinstance(request.get('attempt_id'),str)
        or re.fullmatch(r'[a-f0-9]{32}',request['attempt_id']) is None
        or op=='create_attempt' and not valid_selection(request)
        or 'binding' in required and not valid_binding(request.get('binding'))
        or op=='record_transport_result' and request.get('outcome') not in ('confirmed','failed','unknown')):
        return denied('invalid_request')
    try:
        from .integrator import export_attempts as attempts
        from .integrator.domestic_packages import COMPANY_KEYS
        from .integrator.domestic_dictionaries import dictionary_inputs
        settings={key:os.environ.get(key) for key in COMPANY_KEYS}
        if op=='create_attempt':
            dictionary_inputs(request['portal'])
            item=attempts.create_attempt(**{k:request[k] for k in ('package_id','offer_id','portal','action','attempt_id')},settings=settings)
        elif op=='get_attempt':item=attempts.get_attempt(request['attempt_id'])
        elif op=='record_transport_result':
            item=attempts.record_transport_result(request['attempt_id'],request['binding'],request['outcome'])
        else:
            # Each SSH command has a fresh process/cache. Refresh only when
            # fresh validation is needed, never for lookup or a completed ACK.
            current=attempts.get_attempt(request['attempt_id'])
            if current['binding']!=request['binding']:return denied('invalid_request')
            if (op=='start_transport' and current['state']=='prepared'
                or op=='acknowledge_attempt' and current['state'] in {'transport_confirmed','ack_failed'}):
                dictionary_inputs(current['binding']['portal'])
            function=getattr(attempts,op)  # op is from the fixed whitelist above
            item=function(request['attempt_id'],request['binding'],settings=settings)
        if (not valid_binding(item.get('binding')) or not isinstance(item.get('attempt_id'),str)
            or re.fullmatch(r'[a-f0-9]{32}',item['attempt_id']) is None
            or item.get('state') not in {'prepared','transport_unknown','transport_failed','transport_confirmed','ack_failed','ack_rejected','ack_completed'}):
            return denied('operation_unavailable')
        # No baseline SQL row, raw last_error, private paths or record contents.
        public={k:item[k] for k in ('attempt_id','binding','state')}
        if op=='start_transport':public['can_send']=item.get('can_send') is True
        if op=='acknowledge_attempt' and item.get('already_acknowledged') is True:
            public['already_acknowledged']=True
        if item.get('reason') in {'inputs_or_order_changed','ack_storage_or_verification_unavailable'}:
            public['reason']=item['reason']
        return reply | {'ok':True,'attempt':public}
    except PermissionError:return denied('permission_denied')
    except RuntimeError:return denied('operation_blocked')
    except Exception:return denied('operation_unavailable')


FOREIGN_BINDING_KEYS = (BINDING_KEYS | {'domain','subject','members','transport_profile','input_revision'})


def valid_foreign_binding(value):
    from .integrator.foreign_contract import PROFILES, _id, _sha
    if not isinstance(value,dict) or set(value)!=FOREIGN_BINDING_KEYS: return False
    subject=value.get('subject'); members=value.get('members')
    return (valid_binding({k:value[k] for k in BINDING_KEYS})
        and value['domain']=='foreign' and value['portal'] in PROFILES
        and value['transport_profile']==PROFILES[value['portal']] and _sha(value['input_revision'])
        and isinstance(subject,dict) and set(subject)=={'kind','id'} and _id(subject['id'])
        and isinstance(members,list) and bool(members) and all(_id(i) for i in members)
        and members==sorted(set(members)) and value['offer_id']==members[0]
        and (subject['kind']=='foreign_offer' and members==[subject['id']]
             or subject['kind']=='cyprus_development' and value['portal']=='tabelaofert' and value['action']=='add'))


def dispatch_foreign(request):
    """Trusted OS publisher, not cryptographic evidence that FTP occurred."""
    from .integrator import export_attempts as attempts
    from .integrator import domestic_package_catalog as catalog
    from .integrator.foreign_packages import _selection
    op=request.get('operation')
    reply={'protocol_version':2,'domain':'foreign','operation':op if isinstance(op,str) else None,'ok':False}
    try:
        if type(request.get('protocol_version')) is not int or request['protocol_version']!=2 or request.get('domain')!='foreign':
            raise ValueError('Protocol')
        base={'protocol_version','domain','operation'}
        if op in ('verify','create_attempt'):
            required=base|{'package_id','subject','portal','action'}
            if op=='create_attempt': required.add('attempt_id')
            subject=request.get('subject')
            if not isinstance(subject,dict) or set(subject)!={'kind','id'}: raise ValueError('Subject')
            _selection(subject['kind'],subject['id'],request.get('portal'),request.get('action'))
            if not isinstance(request.get('package_id'),str) or not catalog.ID.fullmatch(request['package_id']): raise ValueError('Package')
        elif op in OPERATIONS:
            required=base|{'attempt_id'}
            if op!='get_attempt': required.add('binding')
            if op=='record_transport_result': required.add('outcome')
        else: raise ValueError('Operation')
        if set(request)!=required: raise ValueError('Fields')
        if op!='verify' and (not isinstance(request.get('attempt_id'),str) or not catalog.ID.fullmatch(request['attempt_id'])): raise ValueError('Attempt')
        if 'binding' in request and not valid_foreign_binding(request['binding']): raise ValueError('Binding')
        if op=='verify':
            # Server revalidates inputs, history, XML and exact artifact bytes.
            from .integrator.foreign_attempt_inputs import package
            from .integrator.input_consistency import input_lock
            with input_lock():
                diagnostic=catalog.verify_package(request['package_id'],domain='foreign')
                if diagnostic['state']!='READY':
                    return reply|{'state':diagnostic['state'],'error':'operation_blocked'}
                binding=package(request['package_id'],None)
                if any(binding[k]!=request[k] for k in ('subject','portal','action')): raise ValueError('Selection')
                _,folder=catalog._root('foreign')
                with catalog._open(folder/request['package_id']/'manifest.json',folder) as stream:
                    raw=stream.read(catalog.MAX_MANIFEST+1)
                return reply|{'ok':True,'state':'READY',**binding,'manifest_size':len(raw),
                              'permissions_checked':True,'checked_at':datetime.now(timezone.utc).isoformat()}
        fields={k:request[k] for k in ('package_id','subject','portal','action','attempt_id')} if op=='create_attempt' else {'attempt_id':request['attempt_id']}
        if 'binding' in request: fields['binding']=request['binding']
        if 'outcome' in request: fields['outcome']=request['outcome']
        item=getattr(attempts,op)(domain='foreign',**fields)
        if not valid_foreign_binding(item.get('binding')): raise ValueError('History binding')
        public={k:item[k] for k in ('attempt_id','binding','state')}
        if op=='start_transport': public['can_send']=item.get('can_send') is True
        for key in ('reason','already_acknowledged'):
            if key in item: public[key]=item[key]
        return reply|{'ok':True,'attempt':public}
    except (ValueError,TypeError,KeyError): return reply|{'error':'invalid_request','state':'BLOCKED'}
    except PermissionError: return reply|{'error':'permission_denied','state':'BLOCKED'}
    except Exception: return reply|{'error':'operation_blocked','state':'BLOCKED'}


def unique_object(pairs):
    result={}
    for key,value in pairs:
        if key in result:raise ValueError('Duplicate JSON key')
        result[key]=value
    return result


def _confirm_package(request):
    from .integrator import domestic_package_catalog as catalog
    from .integrator.domestic_packages import COMPANY_KEYS
    denied={'protocol_version':1,'state':'BLOCKED','reasons':[{'code':'request_invalid','message':'Nieprawidłowe żądanie odbioru.'}]}
    required={'package_id','offer_id','portal','action'}
    if (not isinstance(request,dict) or set(request)!=required
        or not isinstance(request.get('package_id'),str) or not catalog.ID.fullmatch(request['package_id'])
        or type(request.get('offer_id')) is not int or not 0<request['offer_id']<=2**63-1
        or not isinstance(request.get('portal'),str) or request['portal'] not in catalog.preparation.PORTALS
        or request.get('action') not in ('add','delete')):
        return denied
    try:
        root,base=catalog._root()
        path=catalog.package_folder(base,request['package_id'])/'manifest.json'
        def read_manifest():
            with catalog._open(path,base) as stream:
                body=stream.read(catalog.MAX_MANIFEST+1)
            if len(body)>catalog.MAX_MANIFEST:raise ValueError('Manifest limit')
            return body,catalog._manifest(body,request['package_id'])
        before,item=read_manifest()
        if any(item[key]!=request[key] for key in required):
            return {**denied,'state':'INVALID','reasons':[{'code':'selection_mismatch','message':'Paczka nie odpowiada wybranej ofercie, portalowi i akcji.'}]}
        settings={key:os.environ.get(key) for key in COMPANY_KEYS}
        diagnostic=catalog.verify_package(request['package_id'],settings=settings)
        if diagnostic['state']!='READY':
            return {'protocol_version':1,'state':diagnostic['state'],'reasons':diagnostic['reasons']}
        after,current=read_manifest()
        if before!=after or current!=item:
            return {**denied,'state':'INVALID','reasons':[{'code':'artifact_changed','message':'Manifest zmienił się podczas potwierdzania.'}]}
        # Bind exact downloaded bytes to this fresh server-side verification.
        return {'protocol_version':1,'state':'READY',**request,
                'checked_at':datetime.now(timezone.utc).isoformat(),
                'zip_name':item['zip_name'],'zip_size':item['zip_size'],'zip_sha256':item['zip_sha256'],
                'manifest_size':len(after),'manifest_sha256':hashlib.sha256(after).hexdigest(),
                'input_fingerprint':item['input_fingerprint'],
                'permissions_checked':True,'warnings':diagnostic.get('warnings',[]),
                'notice':'Potwierdzenie na chwilę kontroli. Brak gwarancji atomowej aktualności i zgody na późniejszą publikację.'}
    except PermissionError:
        return {'protocol_version':1,'state':'BLOCKED','reasons':[{'code':'permission_denied','message':'Konto SSH nie ma wymaganego dostępu do paczki.'}]}
    except Exception:
        return {'protocol_version':1,'state':'BLOCKED','reasons':[{'code':'verification_unavailable','message':'Nie można potwierdzić aktualności lub dostępu do prywatnej paczki.'}]}


def confirm_package(request):
    from .integrator import domestic_sets as sets
    from .integrator import domestic_storage as storage
    from .integrator.domestic_dictionaries import dictionary_inputs
    required = {'package_id', 'offer_id', 'portal', 'action'}
    if isinstance(request, dict) and set(request) == required and valid_selection(request):
        # Old clients ignore extra receipt fields and still assume a flat path.
        # Never issue READY until a client explicitly declares layout support.
        return {'protocol_version': 1, 'state': 'BLOCKED', 'reasons': [
            {'code': 'receiver_upgrade_required', 'message': 'Odbiorca wymaga aktualizacji magazynu paczek.'}]}
    if (not isinstance(request, dict) or set(request) != required | {'storage_layout'}
            or request.get('storage_layout') != storage.LAYOUT):
        return _confirm_package(request)
    selection = {key: request[key] for key in required}
    if not valid_selection(selection):
        return _confirm_package(selection)
    try:
        dictionary_inputs(selection['portal'])
        with sets.locked():
            _, base = sets._catalog()._root()
            with storage.lookup_scope(base):
                result = _confirm_package(selection)
                if result.get('state') == 'READY':
                    _, base = sets._catalog()._root()
                    result.update(storage_layout=storage.LAYOUT,
                                  artifact_path=storage.receipt_path(base, selection['package_id']))
                    # Persist before issuing the receipt. No end-of-reader signal
                    # exists, so pins still never expire automatically.
                    sets.pin(base, selection['package_id'])
                return result

    except Exception:
        return {'protocol_version': 1, 'state': 'BLOCKED', 'reasons': [
            {'code': 'handoff_unavailable', 'message': 'Nie mozna bezpiecznie udostepnic paczki.'}]}


def main():
    response={'protocol_version':1,'state':'BLOCKED','reasons':[{'code':'verifier_unavailable','message':'Zdalny weryfikator nie jest dostępny w wymaganym środowisku.'}]}
    enabled = os.environ.get('INVESTMENT_EXPORT_DIAGNOSTICS') == '1'
    with performance.capture() if enabled else contextlib.nullcontext(None) as diagnostic:
        try:
            # Same configuration load order as flask_app.py, without create_app().
            with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
                from dotenv import load_dotenv
                from env_loader import use_utf8_environment
                use_utf8_environment()
                load_dotenv(Path(__file__).resolve().parents[1]/'.env',encoding='utf-8-sig')
                body=sys.stdin.buffer.read(MAX_REQUEST+1)
                if len(body)<=MAX_REQUEST:
                    request = json.loads(body,object_pairs_hook=unique_object)
                    response=dispatch_request(request)
                    if diagnostic is not None:
                        operation = request.get('operation') if isinstance(request,dict) else None
                        allowed = OPERATIONS | {'list_sync_tasks','list_sync_offers','verify'}
                        diagnostic['operation'] = operation if isinstance(operation,str) and operation in allowed else 'confirm_or_invalid'
        except Exception:
            pass
        sys.stdout.write(json.dumps(response,ensure_ascii=True,separators=(',',':'))+'\n')
    if diagnostic is not None:
        try:
            sys.stderr.write(json.dumps({'export_performance': diagnostic}, separators=(',', ':'))+'\n')
        except Exception:
            pass
    return 0 if response.get('state')=='READY' or response.get('ok') is True else 1


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