"""InFinBot observed-result suite. Public CME sample test and optional private broker pair check; no trading activation."""
import argparse,gzip,hashlib,json,os,ssl,time,urllib.request,uuid
from pathlib import Path
from infinbot_common import private_dir,atomic_json,timestamp,Rejected
from alpaca_rotation_check import AlpacaCredentialRotationCheck
from cme_datamine_parser import CMEDataMineParser

SAMPLE_URL='https://www.cmegroup.com/files/download/xcme-tick-es-fut-20250312-part-00039-c000.csv'
MAX_SAMPLE=128*1024*1024
SAMPLE_SHA256='c62b5527f57079ee28c1a05184adf03f6cafea41bf3ed48c85c59f1b45a2fe51'

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self,*args,**kwargs):raise Rejected('Public sample redirect blocked')

def fetch_public_sample(directory):
    directory=private_dir(directory);identifier=uuid.uuid4().hex
    target=directory/('cme_public_sample_ES_TSv2_'+identifier+'.csv.gz')
    total=0;h=hashlib.sha256();deadline=time.monotonic()+55
    opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),NoRedirect(),urllib.request.HTTPSHandler(context=ssl.create_default_context()))
    fd=os.open(target,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600)
    try:
        with os.fdopen(fd,'wb') as output,gzip.GzipFile(fileobj=output,mode='wb',mtime=0) as compressed:
            with opener.open(urllib.request.Request(SAMPLE_URL,headers={'Accept-Encoding':'identity'},method='GET'),timeout=15) as response:
                if response.status!=200:raise Rejected('Complete HTTP 200 sample required')
                expected=response.headers.get('Content-Length')
                while True:
                    block=response.read(1024*1024)
                    if not block:break
                    total+=len(block)
                    if total>MAX_SAMPLE or time.monotonic()>deadline:raise Rejected('Sample bounds exceeded')
                    h.update(block);compressed.write(block)
                if not total or expected and total!=int(expected):raise Rejected('Incomplete official sample')
        if h.hexdigest()!=SAMPLE_SHA256:raise Rejected('Official sample version changed; exact-byte review required')
        result=CMEDataMineParser('ES').validate(target,header=True)
        return dict(result,status='OFFICIAL_PUBLIC_CME_SAMPLE_SCHEMA_VALIDATED',sample_path=str(target),
                    source_url=SAMPLE_URL,source_bytes=total,source_sha256=h.hexdigest(),
                    gzip_sha256=hashlib.sha256(target.read_bytes()).hexdigest(),
                    provenance='Official static ES sample, locally gzip compressed; not MES or current worker/trial observations',
                    provider_authentication_tested=False,ledger_modified=False)
    except Exception:
        # Only remove this run's owned incomplete/invalid download, never an existing file or ledger.
        if target.exists():target.unlink()
        raise

def import_public_sample(path,directory):
    source=Path(path)
    if source.is_symlink() or not source.is_file() or source.stat().st_size>32*1024*1024:raise Rejected('Bounded existing public gzip sample required')
    compressed=source.read_bytes();h=hashlib.sha256();total=0
    import io
    with gzip.GzipFile(fileobj=io.BytesIO(compressed)) as f:
        while True:
            block=f.read(1024*1024)
            if not block:break
            total+=len(block)
            if total>MAX_SAMPLE:raise Rejected('Expanded sample exceeds bounds')
            h.update(block)
    if h.hexdigest()!=SAMPLE_SHA256:raise Rejected('Selected file does not match the observed official public sample bytes')
    result=CMEDataMineParser('ES').validate(source,header=True)
    target=private_dir(directory)/('cme_public_sample_ES_TSv2_'+uuid.uuid4().hex+'.csv.gz')
    fd=os.open(target,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
    with os.fdopen(fd,'wb') as f:f.write(compressed);f.flush();os.fsync(f.fileno())
    return dict(result,status='OFFICIAL_PUBLIC_CME_SAMPLE_SCHEMA_VALIDATED',sample_path=str(target),source_url=SAMPLE_URL,
                source_bytes=total,source_sha256=h.hexdigest(),gzip_sha256=hashlib.sha256(compressed).hexdigest(),
                provenance='Exact-byte copy of official static ES sample observed 2026-10-13; not current/MES/worker observations',
                provider_authentication_tested=False,ledger_modified=False)

def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--workspace',default='/Users/bpa/ForesixaQuant')
    p.add_argument('--old-credentials-file');p.add_argument('--new-credentials-file');p.add_argument('--mode',choices=('paper','live'))
    p.add_argument('--sample-only',action='store_true');p.add_argument('--skip-sample',action='store_true')
    p.add_argument('--sample-file',help='Existing exact official public gzip sample; copied only after verification')
    a=p.parse_args()
    try:
        base=Path(a.workspace).absolute()
        if not base.is_dir() or base.is_symlink():raise Rejected('Existing intended workspace required')
        logs=private_dir(base/'enterprise_logs');checks=[]
        if a.sample_only:
            checks.append({'check':'broker_rotation','status':'UNVERIFIED','reason':'Explicitly omitted for public-sample-only diagnostic'})
        elif all((a.old_credentials_file,a.new_credentials_file,a.mode)):
            r=AlpacaCredentialRotationCheck().run(a.old_credentials_file,a.new_credentials_file,a.mode)
            checks.append({'check':'broker_rotation','status':'OBSERVED_CHECK_PASSED' if r['status']=='OLD_401_AND_NEW_AUTHENTICATION_OBSERVED' else 'BLOCKED','result':r})
        else:checks.append({'check':'broker_rotation','status':'UNVERIFIED','reason':'Separate existing private old/new broker pair files and matching mode required; no stored old credentials assumed'})
        if a.skip_sample:checks.append({'check':'datamine_public_sample','status':'UNVERIFIED','reason':'Sample download explicitly skipped'})
        else:
            try:checks.append({'check':'datamine_public_sample','status':'OBSERVED_CHECK_PASSED','result':import_public_sample(a.sample_file,logs) if a.sample_file else fetch_public_sample(logs)})
            except Exception:checks.append({'check':'datamine_public_sample','status':'BLOCKED','reason':'Official sample unavailable/incomplete or parser rejected input; no mock/download success invented'})
        mandatory=[c for c in checks if not (a.sample_only and c['check']=='broker_rotation')]
        observed_pass=all(c['status']=='OBSERVED_CHECK_PASSED' for c in mandatory)
        report={'product':'InFinBot','observed_at':timestamp(),'status':'REQUESTED_OBSERVED_CHECKS_PASSED_PRODUCTION_BINDING_PENDING' if observed_pass else 'VALIDATION_INCOMPLETE',
                'checks':checks,'orders_submitted':0,'production_configuration_changed':False,'live_execution_enabled':False,
                'production_TradingBotEngine_binding':'UNVERIFIED_ACTUAL_CLASS_SOURCE_NOT_AVAILABLE',
                'classification':'Public sample and endpoint authentication diagnostics; not trading clearance'}
        receipt=logs/('infinbot_agent_validation_'+uuid.uuid4().hex+'.json');atomic_json(receipt,report)
        print(json.dumps({'status':report['status'],'receipt_path':str(receipt),'checks':checks,'orders_submitted':0,'production_configuration_changed':False},indent=2))
        return int(not observed_pass)
    except Exception:print(json.dumps({'status':'VALIDATION_BLOCKED','reason':'Workspace/private log directory or input configuration unsafe; no production switch occurred'}));return 1

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