"""run_local.py loads .env.dev (never .env), lets the shell win, and refuses a production configuration.

Each scenario runs in a fresh subprocess in a temporary directory with a copy of run_local.py and a stub flask_app that
reports what it sees (and tries to read a stray .env the way the real flask_app does). No application is created.
"""
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path

REPO = Path(__file__).resolve().parents[1]
STUB = '''
import json, os
from pathlib import Path
from dotenv import load_dotenv
loaded_stray = load_dotenv(Path(__file__).with_name(".env"), encoding="utf-8-sig")   # what the real flask_app does
app = object()
print(json.dumps({"flask_env": os.environ.get("FLASK_ENV"), "marker": os.environ.get("DEV_MARKER"),
                  "stray_marker": os.environ.get("STRAY_MARKER"), "dotenv_disabled": os.environ.get("PYTHON_DOTENV_DISABLED"),
                  "stray_loaded": loaded_stray}))
'''


def run(tmp_path, dev_text=None, stray_text=None, shell=None):
    shutil.copy2(REPO / 'run_local.py', tmp_path / 'run_local.py')
    (tmp_path / 'flask_app.py').write_text(STUB, encoding='utf-8')
    if dev_text is not None:
        (tmp_path / '.env.dev').write_text(dev_text, encoding='utf-8')
    if stray_text is not None:
        (tmp_path / '.env').write_text(stray_text, encoding='utf-8')
    env = {key: value for key, value in os.environ.items() if key not in ('FLASK_ENV', 'DEV_MARKER', 'STRAY_MARKER', 'PYTHON_DOTENV_DISABLED')}
    env.update(shell or {})
    return subprocess.run([sys.executable, '-c', 'import run_local'], cwd=tmp_path, env=env, capture_output=True, text=True, timeout=60)


def seen(result):
    assert result.returncode == 0, result.stderr
    return json.loads(result.stdout.strip().splitlines()[-1])


def test_dev_file_is_loaded_and_the_production_dotenv_is_never_read(tmp_path):
    out = seen(run(tmp_path, dev_text='FLASK_ENV=development\nDEV_MARKER=from-dev-file\n',
                   stray_text='FLASK_ENV=production\nSTRAY_MARKER=from-prod-copy\n'))
    assert out['flask_env'] == 'development' and out['marker'] == 'from-dev-file'
    assert out['stray_marker'] is None and out['stray_loaded'] is False and out['dotenv_disabled'] == '1'


def test_shell_variables_win_over_the_dev_file(tmp_path):
    out = seen(run(tmp_path, dev_text='FLASK_ENV=development\nDEV_MARKER=from-dev-file\n', shell={'DEV_MARKER': 'from-shell'}))
    assert out['marker'] == 'from-shell'


def test_a_production_configuration_is_refused(tmp_path):
    for dev_text, shell in (('FLASK_ENV=production\n', None), ('DEV_MARKER=x\n', {'FLASK_ENV': 'production'})):
        result = run(tmp_path, dev_text=dev_text, shell=shell)
        assert result.returncode != 0 and 'refusing to run a production configuration' in result.stderr
        assert result.stdout == ''                                   # the application module was never imported


def test_missing_dev_file_warns_and_still_ignores_a_stray_dotenv(tmp_path):
    result = run(tmp_path, stray_text='STRAY_MARKER=from-prod-copy\n')
    out = seen(result)
    assert '.env.dev not found' in result.stderr
    assert out['stray_marker'] is None and out['stray_loaded'] is False


def test_run_local_keeps_the_contract_checked_by_the_storage_tests():
    text = (REPO / 'run_local.py').read_text(encoding='utf-8')
    assert 'from flask_app import app' in text and 'serve(app, host="0.0.0.0", port=5000)' in text
