"""Strict portable loading of the R07 canonical JSON and exact partition companion."""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
import re

PACKAGE_ID='SW-REGIONAL-FOUNDATION-R07'
COMPANION='SURFACE_PARTITIONS.json'
PARTITION_FIELDS=('terrain_cap_decomposition','water_decomposition')


def exact_json_bytes(raw):
    def reject(value):raise ValueError('non-finite JSON: '+value)
    def pairs(items):
        result={}
        for key,value in items:
            if key in result:raise ValueError('duplicate JSON key: '+key)
            result[key]=value
        return result
    return json.loads(raw,parse_constant=reject,object_pairs_hook=pairs)


def compact_bytes(data):return (json.dumps(data,ensure_ascii=False,allow_nan=False,separators=(',',':'))+'\n').encode('utf-8')


def split_partitions(data):
    if data.get('package_id')!=PACKAGE_ID:raise ValueError('wrong regional package')
    canonical=dict(data);canonical['schema_version']='1.1.0'
    companion={'schema_version':'1.0.0','package_id':PACKAGE_ID,**{key:canonical[key] for key in PARTITION_FIELDS}}
    raw=compact_bytes(companion);digest=hashlib.sha256(raw).hexdigest()
    for key in PARTITION_FIELDS:canonical[key]={'$ref':COMPANION+'#/'+key,'sha256':digest}
    return canonical,raw


def resolve_partitions(canonical,companion_raw):
    if canonical.get('schema_version')!='1.1.0' or canonical.get('package_id')!=PACKAGE_ID:raise ValueError('unsupported regional format')
    digest=hashlib.sha256(companion_raw).hexdigest()
    for key in PARTITION_FIELDS:
        reference=canonical.get(key)
        if not isinstance(reference,dict) or set(reference)!={'$ref','sha256'}:raise ValueError('partition reference must have exact ref/hash fields')
        if reference['$ref']!=COMPANION+'#/'+key:raise ValueError('unexpected partition artifact path or JSON pointer')
        if not isinstance(reference['sha256'],str) or not re.fullmatch('[0-9a-f]{64}',reference['sha256']) or reference['sha256']!=digest:raise ValueError('partition companion checksum changed')
    companion=exact_json_bytes(companion_raw)
    if not isinstance(companion,dict) or set(companion)!={'schema_version','package_id',*PARTITION_FIELDS}:raise ValueError('unexpected partition companion fields')
    if companion['schema_version']!='1.0.0' or companion['package_id']!=PACKAGE_ID:raise ValueError('wrong partition companion identity')
    if not isinstance(companion['terrain_cap_decomposition'],list) or not isinstance(companion['water_decomposition'],dict):raise ValueError('wrong partition structure')
    resolved=dict(canonical)
    for key in PARTITION_FIELDS:resolved[key]=companion[key]
    return resolved


def load_region(folder):
    folder=Path(folder)
    canonical=exact_json_bytes((folder/'REGIONAL_GEOMETRY.json').read_bytes())
    # Only this fixed sibling is opened; document refs never become arbitrary paths.
    return resolve_partitions(canonical,(folder/COMPANION).read_bytes())


def format_schema():
    properties={key:{'type':'object','required':['$ref','sha256'],'additionalProperties':False,
                     'properties':{'$ref':{'const':COMPANION+'#/'+key},'sha256':{'type':'string','pattern':'^[0-9a-f]{64}$'}}} for key in PARTITION_FIELDS}
    return {'$schema':'https://json-schema.org/draft/2020-12/schema','$id':'urn:lost-souls:sw-regional-foundation:r07:1.1.0',
            'title':'R07 canonical regional geometry with required exact partition companion','type':'object',
            'required':['schema_version','package_id','frame','acceptance','features','meshes',*PARTITION_FIELDS],
            'properties':{'schema_version':{'const':'1.1.0'},'package_id':{'const':PACKAGE_ID},'features':{'type':'array'},'meshes':{'type':'array'},**properties},
            '$defs':{'surface_partitions':{'type':'object','additionalProperties':False,'required':['schema_version','package_id',*PARTITION_FIELDS],
                       'properties':{'schema_version':{'const':'1.0.0'},'package_id':{'const':PACKAGE_ID},'terrain_cap_decomposition':{'type':'array'},'water_decomposition':{'type':'object'}}}},
            '$comment':'Both sha256 values must equal the exact companion bytes. region_io.py enforces that cross-file condition and rejects duplicate/non-finite JSON. Full geometry constraints are checked by the repository validator.'}
