"""Stage 4: read-only hosting preflight."""
from contextlib import closing
import json
import sqlite3
import os

import pytest

from InvestmentManager.integrator import export_job_runner as runner
from InvestmentManager.integrator import export_preflight as preflight
from tests.investmentmanager import qualification_support as support


@pytest.fixture
def box(tmp_path, monkeypatch):
    root = tmp_path / 'InvestmentData'
    root.mkdir()
    monkeypatch.setenv('DATA_DIR', str(root))
    support.init_root(root)
    return root


def snapshot(root):
    """Files outside SQLite sidecars (size, mtime) plus the LOGICAL content of every database: a WAL checkpoint that happens
    when some earlier connection is garbage-collected must not look like a write by the preflight."""
    import hashlib
    result = []
    for path in sorted(root.rglob('*')):
        if not path.is_file() or path.name.endswith(('-wal', '-shm')):
            continue
        if path.suffix == '.db':
            with closing(sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True)) as conn:
                result.append((str(path.relative_to(root)), hashlib.sha256('\n'.join(conn.iterdump()).encode('utf-8')).hexdigest()))
        else:
            result.append((str(path.relative_to(root)), path.stat().st_size, path.stat().st_mtime_ns))
    return result


def by_name(report):
    return {item['name']: item for item in report['checks']}


def test_preflight_reports_every_primitive_and_writes_nothing_inside_data_dir(box):
    before = snapshot(box)
    report = preflight.run()
    assert snapshot(box) == before and report['writes_inside_data_dir'] is False
    checks = by_name(report)
    for name in ('platform', 'file_lock', 'atomic_replace', 'sqlite_version', 'sqlite_wal', 'tls', 'data_dir_access', 'disk_free', 'idb_database'):
        assert name in checks, name
    assert checks['file_lock']['status'] in ('ok', 'warn')                  # warn = Windows fallback, never fail here
    assert checks['atomic_replace']['status'] == 'ok' and checks['idb_database']['status'] == 'ok'
    assert report['verdict'] in ('ok', 'warn')
    assert all(set(item) == {'name', 'status', 'detail'} and item['status'] in ('ok', 'warn', 'fail', 'unknown') for item in report['checks'])


def test_missing_data_dir_and_broken_lock_fail_the_verdict(tmp_path, monkeypatch):
    monkeypatch.delenv('DATA_DIR', raising=False)
    assert by_name(preflight.run())['data_dir']['status'] == 'fail'
    monkeypatch.setattr(preflight, '_lock_probe', lambda directory: ('flock', False))
    report = preflight.run()
    assert by_name(report)['file_lock']['status'] == 'fail' and report['verdict'] == 'fail'


def test_probe_directory_is_private_and_removed(box, monkeypatch):
    seen = []
    original = preflight._lock_probe
    monkeypatch.setattr(preflight, '_lock_probe', lambda directory: (seen.append(directory), original(directory))[1])
    preflight.run()
    assert seen and not os.path.exists(seen[0]) and str(box) not in str(seen[0])


def test_cli_preflight_prints_json_and_exit_code_follows_the_verdict(box, capsys):
    code = runner.main(['preflight'])
    out = json.loads(capsys.readouterr().out)
    assert out['verdict'] in ('ok', 'warn', 'fail') and code == (1 if out['verdict'] == 'fail' else 0)


def test_preflight_never_opens_a_network_connection(box, monkeypatch):
    import socket

    def refuse(*a, **k):
        raise AssertionError('preflight must not use the network')
    monkeypatch.setattr(socket.socket, 'connect', refuse)
    preflight.run()
