"""Local authoritative records; only allowlisted summaries may leave the server."""
from pathlib import Path
import datetime
import os
import shutil
import time

from ..core import absolute, canonical, read_json, require, sha256, write_json


def attempt_record():
    parent=Path('/var/lib/contextra-maintenance/offline-attempts') if os.geteuid()==0 else Path.home()/'.local/state/contextra-offline/attempts'
    name='attempt-'+datetime.datetime.now().strftime('%Y%m%dT%H%M%S')+'-'+str(time.time_ns())
    record=Record(parent/name)
    record.write(dict(release_id=name,phase='STARTED',history=[]))
    return record


class Record:
    def __init__(self, root):
        self.root = absolute(root, no_symlinks=True)

    def write(self, value):
        self.root.mkdir(mode=0o700, parents=True, exist_ok=True)
        require(self.root.stat().st_uid == os.geteuid() and not self.root.stat().st_mode & 0o077,
                'RECORD_PERMISSIONS', '작업 기록 폴더는 실행 계정 전용이어야 합니다.')
        write_json(self.root/'journal.json', value)

    def read(self):
        return read_json(self.root/'journal.json', 16*1024**2)

    def step(self, phase, **values):
        record = self.read()
        record.update(values, phase=phase)
        record.setdefault('history', []).append({'phase': phase, 'time': datetime.datetime.now(datetime.timezone.utc).isoformat()})
        self.write(record)

    def public(self):
        r = self.read()
        # Never export paths, config bodies, arbitrary exception/command output or shell history.
        return {k: r[k] for k in ('release_id', 'package_sha256', 'phase', 'history', 'error_code',
                'command_diagnostic', 'images_before', 'images_after', 'readiness', 'rollback_verified',
                'server', 'backend', 'tool_source_commit', 'settings_result', 'action', 'related_release_id') if k in r}

    def export(self, directory):
        directory = absolute(directory, no_symlinks=True)
        require(directory.is_dir(), 'EXPORT_DIRECTORY', '반출할 기존 폴더를 직접 선택하세요.')
        require(not directory.is_relative_to(self.root), 'EXPORT_DIRECTORY', '작업 기록 폴더 밖으로 반출하세요.')
        public = self.public()
        name = public['release_id']+'-'+datetime.datetime.now().strftime('%Y%m%dT%H%M%S%f')
        target = directory/name
        require(shutil.disk_usage(directory).free >= 10*1024**2, 'EXPORT_SPACE', '반출 공간이 부족합니다. 로컬 기록은 보존됩니다.')
        target.mkdir(mode=0o700)
        write_json(target/'result.json', public, new=True, mode=0o644)
        summary = '# 오프라인 배포 작업 기록\n\n상태: '+public['phase']+'\n\n'
        summary += '설치 성공과 브라우저/알람 수용은 별도입니다. 사용자 피드백은 별도 메모로 추가하세요.\n'
        from ..core import atomic_write
        atomic_write(target/'SUMMARY.ko.md', summary, new=True, mode=0o644)
        hashes = {p.name: sha256(p) for p in target.iterdir() if p.is_file()}
        write_json(target/'SHA256.json', hashes, new=True, mode=0o644)
        require(all(sha256(target/n) == h for n,h in hashes.items()), 'EXPORT_VERIFY', '반출 검증 실패. 로컬 근거를 사용하세요.')
        return target
