"""env_loader.use_utf8_environment: a .env with Polish letters must not take the application down (HTTP 500 on 2026-11-13)
and must not be silently altered, defaulted or skipped.

Production cause: lswsgi has an ASCII filesystem encoding, so ``os.environ[key] = "...ś..."`` (what dotenv.load_dotenv does)
raised UnicodeEncodeError while importing flask_app.py. The real-interpreter scenarios (child process with an ASCII locale)
exist only on POSIX; the in-process tests model the same codec with an ``os._Environ`` built on ASCII codecs.
"""
import os
import subprocess
import sys
from pathlib import Path

import pytest

import env_loader

REPO = Path(__file__).resolve().parents[1]
POLISH = 'Firma Wspólna Łódź ś'


class FakeEnviron(os._Environ):
    """os._Environ with ASCII value codecs (like an interpreter started without LANG); never touches the real process env."""

    def __init__(self):
        def encode(value):
            return value.encode('ascii', 'surrogateescape')

        def decode(value):
            return value.decode('ascii', 'surrogateescape')
        super().__init__({}, encode, decode, encode, decode)

    def __setitem__(self, key, value):                       # same as os._Environ but without os.putenv
        self._data[self.encodekey(key)] = self.encodevalue(value)


def test_unpatched_ascii_environ_fails_like_production():
    environ = FakeEnviron()
    with pytest.raises(UnicodeEncodeError):
        environ['GRUNTGURU_ESTICRM_COMPANY_NAME'] = POLISH


@pytest.mark.skipif(os.name != 'posix', reason='the patch is POSIX only (Windows environments are not byte based)')
def test_patched_ascii_environ_stores_the_exact_value():
    environ = FakeEnviron()
    assert env_loader.use_utf8_environment(environ) is True
    environ['GRUNTGURU_ESTICRM_COMPANY_NAME'] = POLISH
    environ['PLAIN'] = 'ascii value'
    assert environ['GRUNTGURU_ESTICRM_COMPANY_NAME'] == POLISH and environ.get('GRUNTGURU_ESTICRM_COMPANY_NAME') == POLISH
    assert environ._data[b'GRUNTGURU_ESTICRM_COMPANY_NAME'] == POLISH.encode('utf-8')      # exact UTF-8 bytes (what children inherit)
    assert environ['PLAIN'] == 'ascii value'
    assert env_loader.use_utf8_environment(environ) is False                                  # idempotent
    assert environ['GRUNTGURU_ESTICRM_COMPANY_NAME'] == POLISH


@pytest.mark.skipif(os.name != 'posix', reason='POSIX only')
def test_values_already_in_the_environment_are_decoded_consistently():
    environ = FakeEnviron()
    environ._data[b'FROM_PARENT'] = POLISH.encode('utf-8')                                     # inherited from a UTF-8 parent
    assert environ.get('FROM_PARENT') != POLISH                                                # ASCII codec: surrogates (the old behaviour)
    env_loader.use_utf8_environment(environ)
    assert environ.get('FROM_PARENT') == POLISH


def test_utf8_environment_is_left_untouched():
    def encode(value):
        return value.encode('utf-8', 'surrogateescape')

    def decode(value):
        return value.decode('utf-8', 'surrogateescape')
    environ = os._Environ({}, encode, decode, encode, decode)
    before = environ.encodevalue, environ.decodevalue
    assert env_loader.use_utf8_environment(environ) is False
    assert (environ.encodevalue, environ.decodevalue) == before


def test_unsupported_environment_object_is_left_untouched():
    assert env_loader.use_utf8_environment({}) is False                                        # no codec attributes: no change, no error


def test_cpython_still_exposes_the_codec_attributes_the_fix_relies_on():
    # If a Python upgrade renames these, this fails in CI instead of production silently losing the fix.
    if os.name == 'posix':
        assert all(hasattr(os.environ, name) for name in ('encodevalue', 'decodevalue'))


@pytest.mark.skipif(os.name != 'posix', reason='ASCII filesystem encoding can only be forced on POSIX')
@pytest.mark.parametrize('locale', ['ascii', 'utf8'])
def test_real_interpreter_loads_the_polish_value_exactly_with_dotenv_unchanged(tmp_path, locale):
    (tmp_path / '.env').write_bytes(f'GRUNTGURU_ESTICRM_COMPANY_NAME = {POLISH}\nFTP_NO_HOST = no.example.test\nSECRET_KEY = s3\n'.encode('utf-8'))
    child = (
        "import os, subprocess, sys\n"
        "sys.path.insert(0, sys.argv[2])\n"
        "mode = sys.argv[1]\n"
        "from dotenv import load_dotenv\n"
        "import env_loader\n"
        "if mode == 'old':\n"
        "    try:\n"
        "        load_dotenv('.env', encoding='utf-8-sig'); print('NO_ERROR')\n"
        "    except UnicodeEncodeError: print('UnicodeEncodeError')\n"
        "    raise SystemExit\n"
        "print('patched=%s' % env_loader.use_utf8_environment())\n"
        "load_dotenv('.env', encoding='utf-8-sig')\n"
        "name = os.environ.get('GRUNTGURU_ESTICRM_COMPANY_NAME')\n"
        "print('codepoints=' + ','.join(hex(ord(c)) for c in name if ord(c) > 127))\n"
        "print('same_as_getenv=%s ftp=%s secret=%s' % (name == os.getenv('GRUNTGURU_ESTICRM_COMPANY_NAME'), os.environ['FTP_NO_HOST'], os.environ['SECRET_KEY']))\n"
        "print('child_bytes_ok=%s' % (os.environb[b'GRUNTGURU_ESTICRM_COMPANY_NAME'].decode('utf-8').count('\\u0141') == 1))\n"
        "out = subprocess.run([sys.executable, '-c', 'import os;print(len(os.environb[b\"GRUNTGURU_ESTICRM_COMPANY_NAME\"]))'], capture_output=True, text=True)\n"
        "print('grandchild_len=' + out.stdout.strip())\n")
    env = {'PATH': os.environ.get('PATH', '')}
    if locale == 'ascii':
        env.update(LC_ALL='C', LANG='C', PYTHONCOERCECLOCALE='0', PYTHONUTF8='0')
    else:
        env.update(LC_ALL='C.UTF-8', LANG='C.UTF-8')

    def run(mode):
        # No -I/-E: they would ignore PYTHONUTF8/PYTHONCOERCECLOCALE and silently restore a UTF-8 filesystem encoding.
        return subprocess.run([sys.executable, '-c', child, mode, str(REPO)], env=env, cwd=tmp_path, capture_output=True, text=True, timeout=60)
    old, new = run('old'), run('new')
    expected_old = 'UnicodeEncodeError' if locale == 'ascii' else 'NO_ERROR'
    assert old.stdout.strip() == expected_old, (old.stdout, old.stderr)
    assert new.returncode == 0, new.stderr
    lines = dict(line.split('=', 1) for line in new.stdout.split('\n') if '=' in line and ' ' not in line.split('=', 1)[0])
    expected_points = ','.join(hex(ord(c)) for c in POLISH if ord(c) > 127)
    assert lines['codepoints'] == expected_points                                              # every Polish letter intact
    assert 'same_as_getenv=True ftp=no.example.test secret=s3' in new.stdout
    assert 'child_bytes_ok=True' in new.stdout
    assert lines['grandchild_len'] == str(len(POLISH.encode('utf-8')))                         # children inherit the exact bytes
    assert lines['patched'] == str(locale == 'ascii')                                          # UTF-8 locale: nothing changed


def test_executor_and_old_gruntguru_path_see_the_same_polish_value(tmp_path, monkeypatch):
    """The executor (reads the file as UTF-8) and the WSGI/RPC path (os.environ) must agree on the company name."""
    from InvestmentManager.integrator import export_transport_config as config
    from InvestmentManager.integrator import domestic_packages
    path = tmp_path / '.env'
    path.write_bytes(f'GRUNTGURU_ESTICRM_COMPANY_NAME = {POLISH}\n'.encode('utf-8'))
    monkeypatch.setattr(config, 'ENV_FILE', path)
    monkeypatch.delenv('GRUNTGURU_ESTICRM_COMPANY_NAME', raising=False)
    from_file = config.company_settings()['GRUNTGURU_ESTICRM_COMPANY_NAME']
    monkeypatch.setenv('GRUNTGURU_ESTICRM_COMPANY_NAME', POLISH)                                # what load_dotenv leaves after the fix
    from_environ = {key: os.environ.get(key) for key in domestic_packages.COMPANY_KEYS}['GRUNTGURU_ESTICRM_COMPANY_NAME']
    assert from_file == from_environ == POLISH
