"""create_app() bootstrap tests -- legacy mode and fresh, empty external
DATA_DIR -- Storage Path Layer / Phase 2, section 10.

Both scenarios run in an isolated subprocess so the app factory and every
route module are imported fresh with the scenario's DATA_DIR already in the
environment, independent of modules already imported by this pytest
session. (Runtime paths are resolved per call and nothing is created at
import time; see tests/storage/test_startup_dotenv_entrypoint.py for the
.env-driven entry-point contract.)

This deliberately does NOT auto-provision instances/IDB.db or
instances/agents.db with an empty schema -- per section 10, "directory
bootstrap" (creating folders so writers don't crash) is a different
concern from "database provisioning/migration" (creating a working,
query-ready schema), and only the former is in scope here.
"""
import json
import subprocess
import sys
import tempfile
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[2]

_BOOTSTRAP_PROBE_SCRIPT = '''\
import json, os, sys, traceback
from pathlib import Path

sys.path.insert(0, {repo_root!r})
os.environ["FLASK_ENV"] = "development"
os.environ["SECRET_KEY"] = "test"
{data_dir_env_line}

result = {{"ok": False, "error": None, "traceback": None, "route_count": None}}
try:
    from modules.core import storage_paths
    storage_paths.REPO_ROOT = Path({storage_root!r})
    from modules.core.app_factory import create_app
    app = create_app()
    result["ok"] = True
    result["route_count"] = len(app.url_map._rules)
except Exception as exc:
    result["error"] = f"{{type(exc).__name__}}: {{exc}}"
    result["traceback"] = traceback.format_exc()

print(json.dumps(result))
'''


def _run_probe(*, data_dir=None, cwd):
    if data_dir is not None:
        data_dir_env_line = f'os.environ["DATA_DIR"] = {str(data_dir)!r}'
    else:
        data_dir_env_line = 'os.environ.pop("DATA_DIR", None)'

    script = _BOOTSTRAP_PROBE_SCRIPT.format(
        repo_root=str(REPO_ROOT),
        storage_root=str(cwd),
        data_dir_env_line=data_dir_env_line,
    )

    with tempfile.TemporaryDirectory() as script_dir:
        script_path = Path(script_dir) / "probe_create_app.py"
        script_path.write_text(script, encoding="utf-8")
        result = subprocess.run(
            [sys.executable, str(script_path)],
            cwd=cwd,
            capture_output=True,
            text=True,
            timeout=60,
        )
    assert result.returncode == 0, f"subprocess crashed:\\n{result.stderr}"
    return json.loads(result.stdout.strip().splitlines()[-1])


def test_create_app_legacy_mode_in_fresh_subprocess():
    with tempfile.TemporaryDirectory() as fresh_cwd:
        payload = _run_probe(data_dir=None, cwd=fresh_cwd)

    assert payload["ok"] is True, payload.get("traceback")
    # Five intentional additions since FLOOR-2's 161: business landing,
    # foreign fields/sync/active, and offer description. Exact registrations
    # are checked in test_route_inventory_after_legacy_export_removal.
    assert payload["route_count"] == 193  # Includes foreign download, scheduler settings and history, ten export job routes (two D09); exact inventory checked separately


def test_create_app_external_mode_with_fresh_empty_data_dir():
    with tempfile.TemporaryDirectory() as fresh_cwd, tempfile.TemporaryDirectory() as fresh_data_dir:
        payload = _run_probe(data_dir=fresh_data_dir, cwd=fresh_cwd)

    # If this ever starts failing, the assertion message below IS the
    # blocker report required by section 10 -- do not silently work around
    # it by auto-creating database files.
    assert payload["ok"] is True, (
        "create_app() failed to start against a completely fresh, empty "
        f"DATA_DIR. Blocker:\\n{payload.get('traceback')}"
    )
    assert payload["route_count"] == 193  # Includes foreign download, scheduler settings and history, ten export job routes (two D09); exact inventory checked separately
