"""Independent low-latency UI/backend release over the existing review epoch."""
from pathlib import Path
import json
import shutil

from .cluster_targets import digest
from .mask_model_training_data import PROJECT, read, write, require
from .mask_taxonomy_data import REQUESTS, REVIEWS, MANAGED, sources_current, NAMESPACE
from .mask_taxonomy_keyboard_ui import KeyboardGallery, UI_FILES, MIMES
from .mask_taxonomy_review import ASSETS, TaxonomyHandler
from .mask_taxonomy_source_guard import SourceGuard
from .mask_taxonomy_fast_review import FastTaxonomyEditor

SCHEMA='taxonomy-fast-navigation-v4'
SPEC=REQUESTS/'ui_fast_v4.json'
ACTIVE=MANAGED/'fast_navigation_active.json'
CHECKS=MANAGED/'checks_fast_v4_retry1'
IMPLEMENTATIONS=('pallet/mask_taxonomy_source_guard.py','pallet/mask_taxonomy_fast_review.py','pallet/mask_taxonomy_fast_ui.py')


def validate_assets(root,spec):
    root=Path(root).resolve()
    require(spec['schema']==SCHEMA and spec['base_manifest_sha256']==digest(root/'manifest.json'),'Fast UI task binding changed')
    require(set(spec['assets'])==UI_FILES,'Fast UI may only override presentation assets')
    assets={}
    for name,item in spec['assets'].items():
        raw=root/item['path'];path=raw.resolve()
        require(path.is_relative_to(root/'ui_fast_v4') and not raw.is_symlink() and digest(path)==item['sha256'],'Fast UI asset path or bytes changed')
        assets['/'+name]=(path,MIMES[path.suffix],item['sha256'])
    assets['/report_zh.html']=assets['/page.html'];return assets


def build():
    require(not SPEC.exists() and not (REQUESTS/'ui_fast_v4').exists(),'Keep previous performance-release evidence')
    require(sources_current(),'Sources changed before performance UI build')
    folder=REQUESTS/'ui_fast_v4';folder.mkdir(mode=0o700)
    for name in ('page.html','review.js','review.css'):shutil.copyfile(ASSETS/name,folder/name)
    from scripts.build_mask_remaining_direct_requests import build_font
    build_font(folder,(folder/'page.html').read_text()+(folder/'review.js').read_text()+json.dumps(read(REQUESTS/'classes.json'),ensure_ascii=False))
    value=dict(schema=SCHEMA,base_manifest_sha256=digest(REQUESTS/'manifest.json'),
        assets={name:dict(path='ui_fast_v4/'+name,sha256=digest(folder/name)) for name in UI_FILES},
        namespace_and_review_binding_unchanged=True,old_UI_specs_and_native_images_preserved=True,
        prefetch='only_two_adjacent_immutable_originals_bounded_six_images_no_review_metadata_cache',
        source_validation='full_startup_check_then_every_request_SQLite_data_version_and_file_generation_probes_no_TTL',
        changed_sources='single_flight_full_revalidation_fail_closed',
        current_review='fresh_SQL_query_on_every_navigation',
        save='source_probe_before_and_after_validation_original_atomic_expected_revision_append')
    validate_assets(REQUESTS,value);write(SPEC,value)
    print(dict(state='fast_UI_built_pending_acceptance',schema=SCHEMA),flush=True)


class FastGallery(KeyboardGallery):
    def __init__(self,directory=REQUESTS,reviews=REVIEWS,key=None,*,source_guard=None):
        super().__init__(directory,reviews,key)
        self.source_guard=source_guard or SourceGuard.for_gallery(self.manifest_sha256)
        require(self.source_guard.current(),'Full source verification required before serving fast review')
        self.assets.update(validate_assets(self.root,read(SPEC)))
        self.editor=FastTaxonomyEditor(self.editor,self.source_guard)

    def close(self):self.source_guard.close()


class FastHandler(TaxonomyHandler):
    def route(self):
        from urllib.parse import urlsplit
        if urlsplit(self.path).path=='/healthz' and self.command in ('GET','HEAD'):
            return self.json(dict(status='ok',service='pallet_mask_taxonomy_review',targets=self.server.gallery.count,
                publication_version=NAMESPACE,editing_enabled=True,navigation_performance_version=SCHEMA,
                source_change_and_revision_checks_preserved=True))
        return super().route()


def validate_acceptance():
    validate_assets(REQUESTS,read(SPEC));receipt=read(CHECKS/'acceptance.json')
    require(receipt['state']=='passed_fast_navigation_source_invalidation_and_browser_safety' and receipt['manifest_sha256']==digest(REQUESTS/'manifest.json')
        and receipt['ui_spec_sha256']==digest(SPEC) and receipt['production_annotation_POSTs']==0,'Verified performance/safety release required')
    require(all(digest(PROJECT/path)==h for path,h in receipt['implementation_sha256'].items()),'Performance-tested implementation changed')
    require(len(receipt['viewports'])==2 and not receipt['page_errors'] and all(v['keyboard_safety'] and v['fresh_review_after_prefetch'] and v['source_change_409']
        and v['prefetch_failure_safe'] and v['local_navigation_median_ms']<250 for v in receipt['viewports']),'Incomplete fast navigation browser matrix')
    require(receipt['hot_detail_median_ms']<50 and receipt['source_guard_tests_passed'],'Performance/source-guard regression requirements failed')
    return receipt


def active_configuration():
    if not ACTIVE.exists():return None
    value=read(ACTIVE)
    require(value['schema']==SCHEMA and value['ui_spec_sha256']==digest(SPEC) and value['acceptance_sha256']==digest(CHECKS/'acceptance.json')
        and value['manifest_sha256']==digest(REQUESTS/'manifest.json'),'Active performance binding changed')
    validate_acceptance();return value


def activate():
    require(not ACTIVE.exists(),'Do not replace an existing performance release pointer')
    validate_acceptance();require(sources_current(),'Sources changed before fast navigation activation')
    value=dict(schema=SCHEMA,ui_spec_sha256=digest(SPEC),acceptance_sha256=digest(CHECKS/'acceptance.json'),
        manifest_sha256=digest(REQUESTS/'manifest.json'),original_namespace_and_saved_history_unchanged=True)
    write(ACTIVE,value);print(dict(state='verified_fast_navigation_selected_for_next_3412_restart'),flush=True)
