"""Startup through the real flask_app.py entry point with configuration
supplied only by a .env file (Wave A1).

Regression: flask_app.py used to import the app factory before calling
load_dotenv(), and several modules resolved storage_paths / read os.environ
while being imported. With DATA_DIR present only in .env, databases (resolved
per call) went to DATA_DIR while logs, CRM alerts, knowledge-center data and
schedules (resolved at import) fell back into the repository checkout, and
config values such as SECRET_KEY / FLASK_ENV were read before .env existed.

Every scenario runs in a fresh subprocess so no already-imported module can
hide the ordering bug. The real flask_app.py is copied next to a temporary
.env (it loads the .env that sits beside it), the child environment is
stripped of every variable under test, and DATA_DIR always points at a
temporary directory -- never at the developer's real runtime data.
"""
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path

import pytest

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

_ENV_VARS_UNDER_TEST = (
    "DATA_DIR",
    "SECRET_KEY",
    "FLASK_ENV",
    "MATOMO_ENABLED",
    "MATOMO_BASE_URL",
    "MATOMO_SITE_ID",
    "MATOMO_OFFER_DIMENSION_ID",
    "MATOMO_REPORTING_ENABLED",
    "MATOMO_REPORTING_START_DATE",
    "PLATFORM_LOG_RETENTION_MODE",
    "RATELIMIT_STORAGE_URI",
    "FRANCHISE_MEETING_AGENT_ID",
    "FRANCHISE_MEETING_SLOT_MINUTES",
    "FRANCHISE_MEETING_WINDOW_DAYS",
    "FRANCHISE_MEETING_WORKDAY_START_HOUR",
    "FRANCHISE_MEETING_WORKDAY_END_HOUR",
    "MAIL_USERNAME",
    "MAIL_PASSWORD",
    "DB_SHELL_PASSWORD",
)

# Legacy runtime locations inside the checkout that an external-mode startup
# must never create or modify.
_LEGACY_REPO_RUNTIME_PATHS = (
    "logs",
    "instances",
    os.path.join("InvestmentManager", "alerts"),
    os.path.join("InvestmentManager", "knowledge_center"),
    os.path.join("InvestmentManager", "scrapers", "data"),
)

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

sys.path.append({repo_root!r})
{prelude}

result = {{"ok": False, "error": None, "traceback": None}}
try:
    import flask_app
    app = flask_app.app
    result["ok"] = True
    result["route_count"] = len(app.url_map._rules)
    result["secret_key_matches"] = app.config.get("SECRET_KEY") == {expected_secret!r}
    for key in ("DEBUG", "SESSION_COOKIE_SECURE", "MATOMO_ENABLED", "MATOMO_BASE_URL", "MATOMO_SITE_ID",
                "MATOMO_OFFER_DIMENSION_ID", "MATOMO_REPORTING_ENABLED", "MATOMO_REPORTING_START_DATE",
                "PLATFORM_LOG_RETENTION_MODE",
                "FRANCHISE_MEETING_AGENT_ID", "FRANCHISE_MEETING_SLOT_MINUTES"):
        result[key] = app.config.get(key)

    def handler_files(logger):
        return sorted(str(Path(h.baseFilename)) for h in logger.handlers if hasattr(h, "baseFilename"))

    result["log_files"] = {{
        "root": handler_files(logging.getLogger()),
        "access": handler_files(logging.getLogger("access")),
        "access_errors": handler_files(logging.getLogger("access_errors")),
        "login": handler_files(logging.getLogger("login")),
    }}

    from modules.core import storage_paths
    result["db_paths"] = [str(storage_paths.idb_db_path()), str(storage_paths.agents_db_path()),
                          str(storage_paths.crm_clients_db_path()),
                          str(storage_paths.foreign_offers_db_path()),
                          str(storage_paths.platform_logs_db_path())]

    consumers = {{}}
    def collect(name, fn):
        try:
            consumers[name] = str(fn())
        except Exception as exc:
            consumers[name] = "ERROR " + type(exc).__name__
    import InvestmentManager.routes.alerts_system as alerts
    import InvestmentManager.routes.knowledge_center as kc
    import InvestmentManager.routes.agent_panel_scheduler as scheduler
    import InvestmentManager.routes.lead_hunter_seekers as seekers
    collect("alert_file", lambda: alerts.get_alert_file(1))
    collect("notes", lambda: kc._notes_path())
    collect("notifications", lambda: kc._notifications_path())
    collect("notes_backups", lambda: kc._backup_folder())
    collect("schedule_file", lambda: scheduler._schedule_path(1))
    collect("schedule_backups", lambda: scheduler._schedules_backup_folder())
    collect("manual_leads", lambda: seekers._leads_path())
    result["consumer_paths"] = consumers
except BaseException as exc:
    result["error"] = type(exc).__name__ + ": " + str(exc)
    result["traceback"] = traceback.format_exc()

print("PROBE_RESULT " + json.dumps(result))
'''


def _snapshot_repo_runtime_paths():
    snapshot = {}
    for rel in _LEGACY_REPO_RUNTIME_PATHS:
        root = REPO_ROOT / rel
        if not root.exists():
            snapshot[rel] = None
            continue
        snapshot[rel] = sorted(
            (str(p.relative_to(root)), p.stat().st_size, p.stat().st_mtime_ns)
            for p in [root, *root.rglob("*")]
        )
    return snapshot


def _run_entrypoint(tmp_path, dotenv_lines, *, prelude=""):
    """Run the real flask_app.py (copied beside a temporary .env) in a fresh
    interpreter whose environment contains none of the variables under test."""
    entry_dir = tmp_path / "entry"
    entry_dir.mkdir()
    shutil.copy2(REPO_ROOT / "flask_app.py", entry_dir / "flask_app.py")
    (entry_dir / ".env").write_text("\n".join(dotenv_lines) + "\n", encoding="utf-8")

    secret = next((line.split("=", 1)[1] for line in dotenv_lines if line.startswith("SECRET_KEY=")), None)
    probe = entry_dir / "probe_entrypoint.py"
    probe.write_text(
        _PROBE.format(repo_root=str(REPO_ROOT), prelude=prelude, expected_secret=secret),
        encoding="utf-8",
    )

    child_env = {k: v for k, v in os.environ.items() if k not in _ENV_VARS_UNDER_TEST}
    child_env["PYTHONDONTWRITEBYTECODE"] = "1"

    completed = subprocess.run(
        [sys.executable, str(probe)],
        cwd=entry_dir,
        env=child_env,
        capture_output=True,
        text=True,
        timeout=120,
    )
    marker = [line for line in completed.stdout.splitlines() if line.startswith("PROBE_RESULT ")]
    assert marker, f"probe produced no result (rc={completed.returncode}):\n{completed.stderr}"
    return json.loads(marker[-1][len("PROBE_RESULT "):])


def _is_under(path, root):
    try:
        Path(path).resolve().relative_to(Path(root).resolve())
        return True
    except ValueError:
        return False


@pytest.fixture()
def external_startup(tmp_path):
    data_dir = tmp_path / "runtime_data"
    data_dir.mkdir()
    before = _snapshot_repo_runtime_paths()
    payload = _run_entrypoint(
        tmp_path,
        [
            f"DATA_DIR={data_dir}",
            "SECRET_KEY=wave-a1-dotenv-secret",
            "FLASK_ENV=production",
            "MATOMO_ENABLED=false",
            "MATOMO_BASE_URL=https://analytics.investment-nieruchomosci.com/",
            "MATOMO_SITE_ID=1",
            "MATOMO_OFFER_DIMENSION_ID=2",
            "MATOMO_REPORTING_ENABLED=false",
            "MATOMO_REPORTING_START_DATE=2026-11-21",
            "PLATFORM_LOG_RETENTION_MODE=report",
            "FRANCHISE_MEETING_AGENT_ID=202",
            "FRANCHISE_MEETING_SLOT_MINUTES=45",
        ],
    )
    after = _snapshot_repo_runtime_paths()
    assert payload["ok"], payload.get("traceback")
    return payload, data_dir, before, after


def test_entrypoint_starts_with_dotenv_only_configuration(external_startup):
    payload, _, _, _ = external_startup
    # Five intended post-FLOOR-2 additions; exact routes/methods are verified
    # by test_route_inventory_after_legacy_export_removal.
    assert payload["route_count"] == 193  # Includes S3 description preview route, foreign download, scheduler settings and history, ten export job routes (two D09); exact inventory checked separately


def test_secret_key_from_dotenv_reaches_the_app(external_startup):
    payload, _, _, _ = external_startup
    assert payload["secret_key_matches"] is True


def test_environment_backed_config_is_read_after_dotenv(external_startup):
    payload, _, _, _ = external_startup
    # FLASK_ENV=production from .env must select ProdConfig.
    assert payload["DEBUG"] is False
    assert payload["SESSION_COOKIE_SECURE"] is True
    assert payload["MATOMO_ENABLED"] is False
    assert payload["MATOMO_BASE_URL"] == "https://analytics.investment-nieruchomosci.com/"
    assert payload["MATOMO_SITE_ID"] == 1
    assert payload["MATOMO_OFFER_DIMENSION_ID"] == 2
    assert payload["MATOMO_REPORTING_ENABLED"] is False
    assert payload["MATOMO_REPORTING_START_DATE"] == "2026-11-21"
    assert payload["PLATFORM_LOG_RETENTION_MODE"] == "report"
    assert payload["FRANCHISE_MEETING_AGENT_ID"] == 202
    assert payload["FRANCHISE_MEETING_SLOT_MINUTES"] == 45


def test_dotenv_data_dir_is_honoured_by_every_runtime_path_consumer(external_startup):
    payload, data_dir, _, _ = external_startup

    for db_path in payload["db_paths"]:
        assert _is_under(db_path, data_dir), db_path

    log_files = payload["log_files"]
    for name in ("root", "access", "access_errors", "login"):
        assert log_files[name], f"no file handler configured for {name!r} logger"
        for log_file in log_files[name]:
            assert _is_under(log_file, data_dir), (name, log_file)

    consumers = payload["consumer_paths"]
    assert set(consumers) == {
        "alert_file", "notes", "notifications", "notes_backups",
        "schedule_file", "schedule_backups", "manual_leads",
    }
    for name, resolved in consumers.items():
        assert _is_under(resolved, data_dir), (name, resolved)


def test_external_startup_creates_nothing_in_legacy_repo_locations(external_startup):
    _, _, before, after = external_startup
    assert after == before


def test_startup_does_not_seed_crm_runtime_files(external_startup):
    _, data_dir, _, _ = external_startup
    # Only logging (explicitly initialised by create_app) may touch disk at
    # startup; CRM JSON stores are created lazily on first write.
    created = sorted(str(p.relative_to(data_dir)).replace("\\", "/") for p in data_dir.rglob("*") if p.is_file())
    assert all(path.startswith("logs/") for path in created), created
    assert not (data_dir / "crm").exists()


def test_legacy_mode_without_data_dir_still_resolves_under_repo_root(tmp_path):
    fake_repo_root = tmp_path / "fake_repo_root"
    fake_repo_root.mkdir()
    prelude = (
        "from modules.core import storage_paths\n"
        f"storage_paths.REPO_ROOT = Path({str(fake_repo_root)!r})"
    )
    payload = _run_entrypoint(
        tmp_path,
        ["SECRET_KEY=wave-a1-legacy-secret", "FLASK_ENV=development"],
        prelude=prelude,
    )

    assert payload["ok"], payload.get("traceback")
    assert payload["route_count"] == 193  # Includes S3 description preview route, foreign download, scheduler settings and history, ten export job routes (two D09); exact inventory checked separately
    assert payload["secret_key_matches"] is True
    consumers = payload["consumer_paths"]
    assert Path(consumers["alert_file"]) == fake_repo_root / "InvestmentManager" / "alerts" / "1.json"
    assert Path(consumers["manual_leads"]) == (
        fake_repo_root / "InvestmentManager" / "knowledge_center" / "manual_leads.json"
    )
    for log_file in payload["log_files"]["access"]:
        assert _is_under(log_file, fake_repo_root / "logs"), log_file


def test_relative_data_dir_in_dotenv_still_raises_value_error(tmp_path):
    before = _snapshot_repo_runtime_paths()
    payload = _run_entrypoint(
        tmp_path,
        ["DATA_DIR=relative/runtime", "SECRET_KEY=wave-a1-relative-secret", "FLASK_ENV=development"],
    )
    assert payload["ok"] is False
    assert payload["error"].startswith("ValueError"), payload.get("traceback")
    assert _snapshot_repo_runtime_paths() == before


def test_env_config_reads_the_environment_when_called(monkeypatch):
    from modules.core.config import env_config

    monkeypatch.setenv("SECRET_KEY", "set-after-import")
    monkeypatch.setenv("FRANCHISE_MEETING_AGENT_ID", "303")
    monkeypatch.setenv("PLATFORM_LOG_RETENTION_MODE", "enforce")
    config = env_config()
    assert config["SECRET_KEY"] == "set-after-import"
    assert config["FRANCHISE_MEETING_AGENT_ID"] == 303
    assert config["PLATFORM_LOG_RETENTION_MODE"] == "enforce"


def test_platform_retention_mode_distinguishes_default_invalid_and_explicit_off(monkeypatch):
    from modules.core.config import env_config

    monkeypatch.setenv("SECRET_KEY", "retention-mode-test")
    monkeypatch.delenv("PLATFORM_LOG_RETENTION_MODE", raising=False)
    assert env_config()["PLATFORM_LOG_RETENTION_MODE"] == "report"

    monkeypatch.setenv("PLATFORM_LOG_RETENTION_MODE", "not-a-mode")
    assert env_config()["PLATFORM_LOG_RETENTION_MODE"] == "report"

    monkeypatch.setenv("PLATFORM_LOG_RETENTION_MODE", "off")
    assert env_config()["PLATFORM_LOG_RETENTION_MODE"] == "off"

    monkeypatch.delenv("SECRET_KEY")
    monkeypatch.setenv("FLASK_ENV", "production")
    with pytest.raises(RuntimeError):
        env_config()
