"""Exercise safety failures in children; violations must never be hidden."""
import os
from pathlib import Path
import shutil
import subprocess
import sys

import pytest

from modules.core import storage_paths
from tests.peer_repository import idbmanager_root


ROOT = Path(__file__).resolve().parents[1]


def probe(code, *, env=None):
    return subprocess.run([sys.executable, '-B', '-c', code], env=env,
                          capture_output=True, text=True, timeout=30)


def test_inherited_data_is_not_selected():
    assert 'DATA_DIR' not in os.environ
    # Preserve pure path contracts. Actual I/O at this default root is denied.
    assert storage_paths.REPO_ROOT == ROOT
    assert os.environ["INVESTMENT_LEGACY_STORAGE"] == "1"


@pytest.mark.parametrize('operation', [
    "open(target, 'wb')", "__import__('sqlite3').connect(target)",
    "__import__('os').mkdir(target)", "__import__('os').remove(target)",
])
def test_checkout_mutation_is_denied_in_child(operation):
    result = probe(f"target={str(ROOT / 'forbidden-probe')!r};{operation}")
    assert result.returncode != 0
    assert 'TestSafetyViolation' in result.stderr
    assert not (ROOT / 'forbidden-probe').exists()


@pytest.mark.parametrize('operation', [
    "__import__('socket').create_connection(('example.invalid', 443))",
    "__import__('socket').socket().connect(('192.0.2.1', 22))",
    "__import__('socket').gethostbyname('example.invalid')",
])
def test_network_is_denied_before_connection(operation):
    result = probe(operation)
    assert result.returncode != 0
    assert 'P1.1 test safety boundary: network:' in result.stderr


def test_swallowed_violation_is_recorded_and_child_stdout_unchanged():
    result = probe(f"""
import safety
try:
    open({str(ROOT / 'instances' / 'IDB.db')!r}, 'rb')
except BaseException:
    pass
assert safety.VIOLATIONS == ['real runtime data access']
print('recorded')
""")
    assert result.returncode == 0, result.stderr
    assert result.stdout.strip() == 'recorded'


def test_safety_survives_replaced_child_environment(tmp_path):
    env = {key: value for key, value in os.environ.items() if key != 'PYTHONPATH'}
    result = probe("import socket;socket.create_connection(('example.invalid',443))", env=env)
    assert result.returncode != 0
    assert 'TestSafetyViolation' in result.stderr


def test_grandchild_inherits_safety():
    result = probe("""
import subprocess,sys
r=subprocess.run([sys.executable,'-B','-c',
    "import socket;socket.create_connection(('example.invalid',443))"],
    capture_output=True,text=True)
assert r.returncode != 0 and 'TestSafetyViolation' in r.stderr
""")
    assert result.returncode == 0, result.stderr


def test_protected_runtime_sqlite_uri_is_denied():
    uri = (ROOT / 'instances' / 'IDB.db').as_uri() + '?mode=ro'
    result = probe(f"import sqlite3;sqlite3.connect({uri!r},uri=True)")
    assert result.returncode != 0
    assert 'TestSafetyViolation' in result.stderr


def test_replace_cannot_overwrite_checkout(tmp_path):
    source = tmp_path / 'synthetic.txt'
    source.write_text('temporary', encoding='utf-8')
    result = probe(f"import os;os.replace({str(source)!r},{str(ROOT / 'forbidden-probe')!r})")
    assert result.returncode != 0
    assert 'TestSafetyViolation' in result.stderr
    assert source.read_text(encoding='utf-8') == 'temporary'
    assert not (ROOT / 'forbidden-probe').exists()


def test_temporary_sqlite_and_files_remain_available(tmp_path):
    target = tmp_path / 'synthetic.db'
    result = probe(f"import sqlite3; c=sqlite3.connect({str(target)!r});"
                   "c.execute('create table probe (id integer)');c.close()")
    assert result.returncode == 0, result.stderr
    assert target.is_file()


def test_node_harness_cannot_use_network():
    node = shutil.which('node')
    if node is None:
        pytest.skip('Node not installed')
    result = subprocess.run([node, '-e', "require('net').connect(443,'example.invalid')"],
                            capture_output=True, text=True, timeout=10)
    assert result.returncode != 0
    assert 'P1.1 Node test safety boundary' in result.stderr


@pytest.mark.skipif(os.name != 'nt', reason='Python Windows version probe')
def test_readonly_windows_version_probe_is_allowed():
    result = subprocess.run('ver', shell=True, capture_output=True, text=True, timeout=10)
    assert result.returncode == 0
    assert result.stdout.strip()


def test_arbitrary_shell_command_is_denied():
    result = probe("import subprocess;subprocess.run('ver & echo unsafe',shell=True)")
    assert result.returncode != 0
    assert 'TestSafetyViolation' in result.stderr


def test_missing_peer_is_actionable_error(monkeypatch, tmp_path):
    monkeypatch.setenv('TEST_IDBMANAGER_ROOT', str(tmp_path / 'missing-peer'))
    with pytest.raises(pytest.UsageError, match='TEST_IDBMANAGER_ROOT'):
        idbmanager_root()


def test_relative_peer_is_rejected(monkeypatch):
    monkeypatch.setenv('TEST_IDBMANAGER_ROOT', 'relative/peer')
    with pytest.raises(pytest.UsageError, match='absolute path'):
        idbmanager_root()
