"""Read-only hosting preflight for the export executor (Stage 4). CLI: export_job_runner preflight.

Answers, for the machine it runs on: are the primitives the executor relies on (non-blocking file locks,
atomic replace, SQLite WAL/locking, process limits, free space, TLS) available and behaving? It never
writes inside DATA_DIR and never touches a portal: probes use a private temporary directory that is
removed afterwards; DATA_DIR is only inspected (permission flags, free space, database header).
Importing this module performs no I/O.
"""
import os
import platform
import shutil
import sqlite3
import stat
import sys
import tempfile
from contextlib import closing
from pathlib import Path

OK, WARN, FAIL, UNKNOWN = 'ok', 'warn', 'fail', 'unknown'
MIN_FREE_BYTES = 256 * 1024 * 1024
MIN_SQLITE = (3, 31, 0)           # advisory: the stores use partial indexes, triggers and strftime('%f'); no hard floor found


def _check(name, status, detail):
    return {'name': name, 'status': status, 'detail': detail}


def _lock_probe(directory):
    """Two independent open file descriptions: the second non-blocking exclusive lock must be refused."""
    path = Path(directory) / 'probe.lock'
    first = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
    second = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
    try:
        if os.name == 'posix':
            import fcntl
            fcntl.flock(first, fcntl.LOCK_EX | fcntl.LOCK_NB)
            try:
                fcntl.flock(second, fcntl.LOCK_EX | fcntl.LOCK_NB)
                contended = False
            except BlockingIOError:
                contended = True
            fcntl.flock(first, fcntl.LOCK_UN)
            fcntl.flock(second, fcntl.LOCK_EX | fcntl.LOCK_NB)           # free again after release
            return 'flock', contended
        import msvcrt
        msvcrt.locking(first, msvcrt.LK_NBLCK, 1)
        try:
            msvcrt.locking(second, msvcrt.LK_NBLCK, 1)
            contended = False
        except OSError:
            contended = True
        msvcrt.locking(first, msvcrt.LK_UNLCK, 1)
        return 'msvcrt.locking', contended
    finally:
        os.close(first)
        os.close(second)


def _locks(temp):
    try:
        method, contended = _lock_probe(temp)
    except Exception as exc:
        return _check('file_lock', FAIL, f'lock probe failed: {type(exc).__name__}')
    if not contended:
        return _check('file_lock', FAIL, f'{method}: a second non-blocking lock was NOT refused (no mutual exclusion)')
    if os.name != 'posix':
        return _check('file_lock', WARN, f'{method} works, but production must be verified on the POSIX flock path')
    return _check('file_lock', OK, 'flock LOCK_EX|LOCK_NB refuses a second holder and is re-acquirable after release')


def _atomic(temp):
    try:
        target = Path(temp) / 'atomic.json'
        for index in range(3):
            fd, name = tempfile.mkstemp(prefix='.probe-', dir=temp)
            with os.fdopen(fd, 'w', encoding='utf-8') as stream:
                stream.write(str(index))
                stream.flush()
                os.fsync(stream.fileno())
            os.replace(name, target)
        if target.read_text(encoding='utf-8') != '2':
            return _check('atomic_replace', FAIL, 'os.replace did not replace the target')
        if os.name == 'posix':
            directory = os.open(temp, os.O_RDONLY | os.O_DIRECTORY)
            try:
                os.fsync(directory)
            finally:
                os.close(directory)
        return _check('atomic_replace', OK, 'tmp+fsync+os.replace (and directory fsync on POSIX) behave')
    except Exception as exc:
        return _check('atomic_replace', FAIL, f'atomic replace probe failed: {type(exc).__name__}')


def _sqlite(temp):
    version = sqlite3.sqlite_version_info
    results = [_check('sqlite_version', OK if version >= MIN_SQLITE else WARN,
                      f'SQLite {sqlite3.sqlite_version} (advisory floor {".".join(map(str, MIN_SQLITE))})')]
    try:
        path = Path(temp) / 'probe.db'
        with closing(sqlite3.connect(path)) as conn:
            mode = conn.execute('PRAGMA journal_mode=WAL').fetchone()[0]
            conn.execute('CREATE TABLE t(x)')
            conn.execute('INSERT INTO t VALUES (1)')
            conn.commit()
        results.append(_check('sqlite_wal', OK if mode == 'wal' else WARN,
                              f'journal_mode=WAL request returned {mode} (on this temp filesystem)'))
    except Exception as exc:
        results.append(_check('sqlite_wal', FAIL, f'SQLite probe failed: {type(exc).__name__}'))
    return results


def _data_dir():
    from modules.core import storage_paths
    root = storage_paths.data_dir()
    if root is None:
        return [_check('data_dir', FAIL, 'DATA_DIR is not configured')]
    results = []
    root = Path(root)
    if not root.is_dir():
        return [_check('data_dir', FAIL, 'DATA_DIR does not exist')]
    unsafe = [part for part in (root, *root.parents) if part.is_symlink()]
    results.append(_check('data_dir_links', FAIL if unsafe else OK, 'symbolic link in the DATA_DIR path' if unsafe else 'no symbolic links in the DATA_DIR path'))
    results.append(_check('data_dir_access', OK if os.access(root, os.R_OK | os.W_OK | os.X_OK) else FAIL,
                          'read/write/search permission flags for the current user (flags only, nothing written)'))
    mode = stat.S_IMODE(root.stat().st_mode) if os.name == 'posix' else None
    if mode is not None and mode & 0o022:
        results.append(_check('data_dir_mode', WARN, f'DATA_DIR is group/world writable (mode {mode:o})'))
    free = shutil.disk_usage(root).free
    results.append(_check('disk_free', OK if free >= MIN_FREE_BYTES else WARN, f'{free // 1048576} MiB free (warn below {MIN_FREE_BYTES // 1048576})'))
    database = root / 'databases' / 'IDB.db'
    if database.is_file():
        try:
            with closing(sqlite3.connect(f'{database.as_uri()}?mode=ro', uri=True, timeout=1)) as conn:
                results.append(_check('idb_database', OK, f'IDB.db opens read-only; journal_mode={conn.execute("PRAGMA journal_mode").fetchone()[0]}, '
                                                           f'size {database.stat().st_size // 1024} KiB'))
        except sqlite3.Error as exc:
            results.append(_check('idb_database', FAIL, f'IDB.db cannot be opened read-only: {type(exc).__name__}'))
    else:
        results.append(_check('idb_database', WARN, 'IDB.db not present yet'))
    return results


def _limits():
    if os.name != 'posix':
        return [_check('process_limits', UNKNOWN, 'resource limits are only inspected on POSIX; measure on the host')]
    import resource
    out = []
    for name, label, floor in (('RLIMIT_NOFILE', 'open files', 256), ('RLIMIT_NPROC', 'processes', 16)):
        soft, hard = resource.getrlimit(getattr(resource, name))
        text = 'unlimited' if soft == resource.RLIM_INFINITY else str(soft)
        out.append(_check('limit_' + label.replace(' ', '_'), OK if soft == resource.RLIM_INFINITY or soft >= floor else WARN, f'{label}: soft {text} (floor {floor})'))
    for name, label in (('RLIMIT_AS', 'address space'), ('RLIMIT_CPU', 'cpu seconds'), ('RLIMIT_FSIZE', 'file size')):
        soft, _ = resource.getrlimit(getattr(resource, name))
        out.append(_check('limit_' + label.replace(' ', '_'), OK if soft == resource.RLIM_INFINITY else WARN,
                          f'{label}: {"unlimited" if soft == resource.RLIM_INFINITY else soft} (a finite value must exceed the executor peak measured on the host)'))
    return out


def _tls():
    try:
        import ssl
        context = ssl.create_default_context()
        verifying = context.verify_mode == ssl.CERT_REQUIRED and context.check_hostname
        return _check('tls', OK if verifying else WARN, f'{ssl.OPENSSL_VERSION}; default context verifies certificates and hostnames: {verifying}')
    except Exception as exc:
        return _check('tls', FAIL, f'ssl module unavailable: {type(exc).__name__}')


def _symlink(temp):
    try:
        target = Path(temp) / 'target'
        target.write_text('x', encoding='utf-8')
        os.symlink(target, Path(temp) / 'link')
        return _check('symlink_support', OK, 'symlinks can be created (the guards that reject links are testable)')
    except (OSError, NotImplementedError):
        return _check('symlink_support', WARN, 'symlinks cannot be created here; link-rejection guards cannot be exercised')


def run():
    """List of checks plus an overall verdict: fail > warn/unknown > ok. Safe to run on production (read-only)."""
    checks = [_check('platform', OK, f'{platform.system()} {platform.release()} / Python {sys.version.split()[0]} / {os.name}')]
    with tempfile.TemporaryDirectory(prefix='export-preflight-') as temp:
        checks.append(_locks(temp))
        checks.append(_atomic(temp))
        checks.extend(_sqlite(temp))
        checks.append(_symlink(temp))
    checks.extend(_limits())
    checks.append(_tls())
    try:
        checks.extend(_data_dir())
    except Exception as exc:
        checks.append(_check('data_dir', FAIL, f'inspection failed: {type(exc).__name__}'))
    statuses = {item['status'] for item in checks}
    verdict = FAIL if FAIL in statuses else WARN if statuses & {WARN, UNKNOWN} else OK
    return {'verdict': verdict, 'checks': checks, 'writes_inside_data_dir': False}
