"""Strictly documentation-only Auralis 0.46.8 publisher; never starts/stops the scheduled watcher.

Root must stop the existing publisher first. Without --publish this builds a
local plan and only reads the remote manifest. Uses the existing site Builder
and unchanged remote_apply.py, with native OpenSSH for all transfers.
  python Tools/Publish-Production0468.py
  python Tools/Publish-Production0468.py --publish
"""
from __future__ import annotations
import argparse
import ast
import contextlib
from datetime import datetime, timezone
import hashlib
import io
import json
import os
from pathlib import Path, PurePosixPath
import re
import shlex
import shutil
import subprocess
import tarfile
import types
import uuid

ROOT = Path(__file__).resolve().parents[1]
PUBLISHER = ROOT / 'Tools/WebPublishing'
WORK = ROOT / 'Tools/.publish-production-0468'
DOCS = ROOT / 'Docs/Angel-Land-Story'
VERSION = '0.46.8'
ALLOWED_REMOTE = '/opt/gaming.hostingcenter.at/public'
ALLOWED_HOST = 'dretzl@185.229.88.77'
REMOTE = HOST = KEY = None
KNOWN_HOSTS = Path.home() / '.ssh/known_hosts'
PREFIX = 'angel-land-story/'
CREATION_FLAGS = 0x08000000 if os.name == 'nt' else 0


def require(value, message):
    if not value:
        raise RuntimeError(message)


def digest(path):
    with path.open('rb') as stream:
        return hashlib.file_digest(stream, 'sha256').hexdigest()


def write_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    temp = path.with_name(path.name + '.tmp')
    temp.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
    temp.replace(path)


def existing_connection():
    # Inspect just the unchanged publisher's explicit connection constants;
    # no import, scheduled task action, password/key-content read or config edit.
    global REMOTE, HOST, KEY
    source = (PUBLISHER / 'publish.py').read_text(encoding='utf-8-sig')
    tree = ast.parse(source)
    remote_nodes = [n for n in tree.body if isinstance(n, ast.Assign)
                    and any(isinstance(t, ast.Name) and t.id == 'REMOTE' for t in n.targets)]
    key_nodes = [n for n in tree.body if isinstance(n, ast.Assign)
                 and any(isinstance(t, ast.Name) and t.id == 'KEY' for t in n.targets)]
    require(len(remote_nodes) == len(key_nodes) == 1, 'Existing publisher connection constants are ambiguous.')
    remote = ast.literal_eval(remote_nodes[0].value)
    key_expression = ast.unparse(key_nodes[0].value)
    require(key_expression == "Path.home() / '.ssh/gaming_docs_rsa'", 'Existing publisher SSH key path changed; review first.')
    connections = [n for n in ast.walk(tree) if isinstance(n, ast.Call)
                   and isinstance(n.func, ast.Attribute) and n.func.attr == 'connect'
                   and n.args and isinstance(n.args[0], ast.Constant) and isinstance(n.args[0].value, str)]
    require(len(connections) == 1, 'Existing publisher SSH destination is ambiguous.')
    users = [k.value for k in connections[0].keywords if k.arg == 'username']
    require(len(users) == 1, 'Existing publisher SSH user is ambiguous.')
    host = ast.literal_eval(users[0]) + '@' + connections[0].args[0].value
    require(host == ALLOWED_HOST and remote == ALLOWED_REMOTE,
            'This release publisher allows only the existing gaming.hostingcenter.at destination.')
    HOST, REMOTE, KEY = host, remote, Path.home() / '.ssh/gaming_docs_rsa'


@contextlib.contextmanager
def watcher_stopped():
    # Hold the publisher's existing byte lock throughout the operation, including
    # transfer. A scheduled restart cannot enter its publication cycle meanwhile.
    require(os.name == 'nt', 'This tool requires the Windows publisher lock.')
    import msvcrt
    lock_path = PUBLISHER / '.state/publisher.lock'
    require(lock_path.is_file(), 'Existing watcher lock is missing; cannot establish exclusivity.')
    with lock_path.open('r+b') as lock:
        lock.seek(0)
        try:
            msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
        except OSError as error:
            raise RuntimeError('Publisher is running. Stop Gaming Docs Publisher before retrying.') from error
        try:
            yield
        finally:
            lock.seek(0)
            msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)


def command(args, data=None):
    result = subprocess.run(args, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                            creationflags=CREATION_FLAGS)
    require(result.returncode == 0, result.stderr.decode('utf-8', errors='replace').strip()
            or 'Command failed: ' + Path(args[0]).name)
    return result.stdout


def ssh_options():
    require(KEY.is_file() and KNOWN_HOSTS.is_file(), 'Existing SSH key/known_hosts is missing.')
    return ['-i', str(KEY), '-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes',
            '-o', 'StrictHostKeyChecking=yes', '-o', 'UserKnownHostsFile=' + str(KNOWN_HOSTS),
            '-o', 'ConnectTimeout=20', '-o', 'ServerAliveInterval=20', '-o', 'ServerAliveCountMax=3']


def ssh(remote_command, data=None):
    executable = shutil.which('ssh.exe') or shutil.which('ssh')
    require(executable, 'Native OpenSSH ssh is unavailable.')
    return command([executable, *ssh_options(), HOST, remote_command], data)


def scp(source, remote_path):
    executable = shutil.which('scp.exe') or shutil.which('scp')
    require(executable, 'Native OpenSSH scp is unavailable.')
    command([executable, '-q', *ssh_options(), str(source), HOST + ':' + remote_path])


def remote_manifest():
    script = ("from pathlib import Path\nimport json\n"
              f"p=Path({REMOTE!r})/'.publish-manifest.json'\n"
              "print(p.read_text() if p.exists() else '{}')\n")
    value = json.loads(ssh('python3 -', script.encode('utf-8')))
    require(isinstance(value, dict), 'Remote manifest is not an object.')
    return value


def build_files(report_path, previous):
    # Bind only the Builder's state directory differently in memory. Neither
    # WebPublishing source nor its state/manifest/cache files are overwritten.
    source_path = PUBLISHER / 'publish.py'
    source = source_path.read_text(encoding='utf-8-sig')
    binding = "STATE = HERE / '.state'"
    require(source.count(binding) == 1, 'Upstream Builder state binding changed; review this adapter.')
    module = types.ModuleType('auralis_scoped_builder_0468')
    module.__file__ = str(source_path)
    exec(compile(source.replace(binding, 'STATE = Path(' + repr(str(WORK)) + ')'), str(source_path), 'exec'), module.__dict__)
    matches = [c for c in module.PROJECTS if c['slug'] == 'angel-land-story']
    require(len(matches) == 1, 'Existing Auralis publishing project is ambiguous.')
    cfg = matches[0]
    require(Path(cfg['root']).resolve() == ROOT and cfg['docs'] == 'Docs/Angel-Land-Story', 'Unexpected Auralis source root.')
    module.rebuild_reader()  # Existing reader entry point uses the original project index.
    module.PROJECTS = [dict(cfg)]
    original_eligible = module.Builder.eligible
    module.Builder.eligible = lambda self, path, project: (not path.resolve().is_relative_to(ROOT / 'Builds')
        and path.suffix.lower() in module.PUBLIC_TYPES and original_eligible(self, path, project))
    original_add = module.Builder.add
    def add_document(self, path, project):
        resolved = path.resolve()
        if resolved.is_relative_to(ROOT / 'Builds'):
            # Preserve only a previously published historical link. Never put
            # its package in the local candidate list or transfer snapshot.
            remote = PREFIX + '_references/' + resolved.relative_to(ROOT).as_posix()
            return remote if remote in previous else None
        return original_add(self, path, project)
    module.Builder.add = add_document
    builder = module.Builder()
    candidates = builder.build()
    files = {}
    for rel, path in candidates.items():
        if not rel.startswith(PREFIX) or path.resolve() == report_path.resolve():
            continue
        require('..' not in PurePosixPath(rel).parts and not PurePosixPath(rel).is_absolute(), 'Unsafe output path.')
        resolved = path.resolve()
        require(not path.is_symlink() and resolved.is_relative_to(ROOT), 'Linked/outside output source: ' + rel)
        # The user deploys Website-v1/the auralis main site personally. This
        # adapter can upload documentation; every build/package is excluded.
        if (resolved.is_relative_to((ROOT / 'Docs/Website-v1').resolve())
                or rel.startswith(PREFIX + '_references/Docs/Website-v1/')):
            continue
        if not resolved.is_relative_to(ROOT / 'Builds') and path.suffix.lower() in module.PUBLIC_TYPES:
            files[rel] = path
    require(files and all('/Builds/' not in rel and path.suffix.lower() not in {'.zip', '.exe', '.dll', '.sha256'} for rel, path in files.items()), 'Documentation-only boundary violated.')
    return files


def run(publish, report_path, report):
    existing_connection()
    require(report_path.is_relative_to((DOCS / f'qa/{VERSION}').resolve()), 'Upload report must remain inside the current release evidence directory.')
    with watcher_stopped():
        previous = remote_manifest()
        files = build_files(report_path, previous)
        changed = {}
        # Freeze changed documentation before transfer.
        # Production may resume once this local snapshot is complete. The
        # transfer and remote manifest describe these exact copied bytes.
        snapshot = WORK / ('snapshot-' + uuid.uuid4().hex)
        for rel, path in list(files.items()):
            meta = {'sha256': digest(path), 'size': path.stat().st_size}
            old = previous.get(rel, {})
            if any(old.get(key) != value for key, value in meta.items()):
                frozen = snapshot / rel
                frozen.parent.mkdir(parents=True, exist_ok=True)
                shutil.copyfile(path, frozen)
                files[rel] = frozen
                meta = {'sha256': digest(frozen), 'size': frozen.stat().st_size}
                changed[rel] = {**old, **meta}
        print('Document snapshot completed; subsequent source changes cannot restart this transfer.', flush=True)
        merged = dict(previous)
        merged.update(changed)  # Never infer deletions from this deliberately partial site inventory.
        report.update(status='planned', documentationOnly=True, buildFilesTransferred=0, version=VERSION, host=HOST, webroot=REMOTE,
                      changedFiles=changed, transferredBytes=sum(m['size'] for m in changed.values()),
                      preservedManifestEntries=len(previous) - len(set(changed) & set(previous)), deletions=0)
        write_json(report_path, report)
        print(f"Auralis only: {len(changed)} changed files, {report['transferredBytes']:,} content bytes; zero deletions.", flush=True)
        if not publish:
            return
        if changed:
            stage = REMOTE + '/.incoming-auralis-0468-' + datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S') + '-' + uuid.uuid4().hex[:8]
            report.update(status='uploading', stage=stage)
            write_json(report_path, report)
            ssh('mkdir -m 700 -- ' + shlex.quote(stage))
            payload = WORK / ('docs-' + uuid.uuid4().hex + '.tar')
            try:
                with tarfile.open(payload, 'w') as tar:
                    for rel in sorted(changed):
                        info = tarfile.TarInfo(rel)
                        info.size = files[rel].stat().st_size
                        info.mode = 0o644
                        with files[rel].open('rb') as stream:
                            tar.addfile(info, stream)
                    data = json.dumps(merged, ensure_ascii=False).encode('utf-8')
                    info = tarfile.TarInfo('.publish-manifest.json')
                    info.size, info.mode = len(data), 0o600
                    tar.addfile(info, io.BytesIO(data))
                scp(payload, stage + '/.docs.tar')
            finally:
                payload.unlink(missing_ok=True)
            ssh('tar -xf ' + shlex.quote(stage + '/.docs.tar') + ' -C ' + shlex.quote(stage)
                + ' && rm -- ' + shlex.quote(stage + '/.docs.tar'))
            require(remote_manifest() == previous, 'Remote manifest changed during transfer; staged upload retained, nothing applied.')
            helper = (PUBLISHER / 'remote_apply.py').read_bytes()
            report['applyResult'] = ssh('python3 - ' + shlex.quote(stage), helper).decode('utf-8').strip()
        # Hash the actual documentation bytes on the server.
        expected = {rel: merged[rel] for rel in changed}
        script = ("from pathlib import Path\nimport hashlib,json\n"
                  f"root=Path({REMOTE!r})\nexpected=json.loads({json.dumps(expected)!r})\nresult={{}}\n"
                  "for rel,meta in expected.items():\n"
                  " p=root/rel\n with p.open('rb') as f: sha=hashlib.file_digest(f,'sha256').hexdigest()\n"
                  " size=p.stat().st_size\n assert sha==meta['sha256'] and size==meta['size'],rel\n"
                  " result[rel]={'sha256':sha,'size':size}\n"
                  "print(json.dumps(result))\n")
        report['serverVerifiedFiles'] = json.loads(ssh('python3 -', script.encode('utf-8')))
        require(remote_manifest() == merged, 'Final remote manifest differs from the no-deletion merged manifest.')
        report.update(status='published', completedUtc=datetime.now(timezone.utc).isoformat())
        write_json(report_path, report)
        print('Published and server SHA-256 verified. Report: ' + str(report_path), flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--publish', action='store_true', help='Transfer/apply the scoped plan after verification.')
    parser.add_argument('--report', type=Path, default=DOCS / f'qa/{VERSION}/upload-report.json')
    args = parser.parse_args()
    require(args.report.resolve().is_relative_to((DOCS / f'qa/{VERSION}').resolve()),
            'Upload report must remain inside the current release evidence directory.')
    report = {'startedUtc': datetime.now(timezone.utc).isoformat(), 'status': 'starting'}
    try:
        run(args.publish, args.report.resolve(), report)
    except Exception as error:
        report.update(status='failed', error=str(error))
        write_json(args.report.resolve(), report)
        raise


if __name__ == '__main__':
    main()
