"""Regression tests for the removal of the legacy portal export engine from
InvestmentWebsite (InvestmentManager/integrator/: FTP upload, XML/ZIP
packaging, the /crm/integrator/portals/... routes, and their associated
frontend in offers.html/offers_actions.js).

Context: the old integrator engine/routes were removed before migration.
The authoritative generator now lives in InvestmentManager/export_engine;
IDBManager receives prepared packages and transports them. These tests
document that the old engine remains removed:
  - the app still starts and serves the public site and CRM login,
  - the two legacy routes are gone,
  - the two ACTIVE shared features that used to live in the same
    InvestmentManager/integrator/ namespace (portal sync state, Otodom
    dictionaries) are still importable and working,
  - no code anywhere in InvestmentWebsite still reads FTP_*,
    INTEGRATOR_DOTENV_FILE or IMAGES_BASE_PATH.
(Update 2026-11: the CRM executor InvestmentManager/integrator/export_transport_config.py is now the only reader of FTP_<PROFILE>_*;
.env.example lists exactly those keys, see test_env_example_has_no_legacy_integrator_override_entries_and_only_executor_ftp_keys.)

No real FTP connections or external HTTP requests are made by any test
here (Otodom's urllib call is monkeypatched).
"""
import os
import re
import sqlite3
from pathlib import Path
from urllib.error import URLError

import pytest

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


# ---------------------------------------------------------------------------
# create_app() / public site / CRM still work.
# ---------------------------------------------------------------------------

def _create_legacy_homepage_databases(root: Path):
    """Provision only the legacy-mode SQLite state GET / needs."""
    instances_dir = root / "instances"
    instances_dir.mkdir()

    with sqlite3.connect(instances_dir / "IDB.db") as conn:
        conn.executescript(
            """
            CREATE TABLE EstateData (
                ID INTEGER PRIMARY KEY,
                Status_oferty TEXT
            );
            CREATE TABLE Localization (
                ID INTEGER PRIMARY KEY,
                Wojewodztwo TEXT
            );
            INSERT INTO EstateData (ID, Status_oferty)
            VALUES (1, 'aktywna');
            INSERT INTO Localization (ID, Wojewodztwo)
            VALUES (1, 'Pomorskie');
            """
        )

    with sqlite3.connect(instances_dir / "agents.db") as conn:
        conn.executescript(
            """
            CREATE TABLE agents_v2 (
                id INTEGER PRIMARY KEY,
                first_name TEXT,
                last_name TEXT,
                email TEXT,
                phone TEXT,
                license TEXT,
                is_active INTEGER
            );
            CREATE TABLE branches_v2 (
                id INTEGER PRIMARY KEY,
                name TEXT,
                is_active INTEGER
            );
            CREATE TABLE agent_branches_v2 (
                agent_id INTEGER,
                branch_id INTEGER
            );
            CREATE TABLE roles_v2 (
                id INTEGER PRIMARY KEY,
                name TEXT
            );
            CREATE TABLE agent_roles_v2 (
                agent_id INTEGER,
                role_id INTEGER
            );
            INSERT INTO agents_v2
                (id, first_name, last_name, email, phone, license, is_active)
            VALUES
                (103, 'Test', 'Agent', 'agent@example.test', '123456789', 'LIC-103', 1);
            INSERT INTO branches_v2 (id, name, is_active)
            VALUES (1, 'Test Branch', 1);
            INSERT INTO agent_branches_v2 (agent_id, branch_id)
            VALUES (103, 1);
            INSERT INTO roles_v2 (id, name)
            VALUES (1, 'Doradca');
            INSERT INTO agent_roles_v2 (agent_id, role_id)
            VALUES (103, 1);
            """
        )


@pytest.fixture()
def legacy_homepage_client(tmp_path, monkeypatch):
    from modules.core import storage_paths
    from modules.core.app_factory import create_app
    from modules.investment import functions as investment_functions

    monkeypatch.delenv("DATA_DIR", raising=False)
    monkeypatch.setattr(storage_paths, "REPO_ROOT", tmp_path)
    _create_legacy_homepage_databases(tmp_path)
    investment_functions.get_estates_count_by_wojewodztwo.cache_clear()
    investment_functions.get_agent_card_data.cache_clear()

    app = create_app()
    app.config.update(TESTING=True)
    yield app.test_client()

    investment_functions.get_estates_count_by_wojewodztwo.cache_clear()
    investment_functions.get_agent_card_data.cache_clear()

def test_create_app_still_builds(app):
    assert app.name == "modules.core.app_factory"


def test_route_inventory_after_legacy_export_removal(app):
    # 154 = 156 (before this removal) - 2 (package, upload).
    # +3 again as of Storage Path Layer Phase 2 (blueprints/media/media.py
    # adds offer_media + agent_avatar; offer_catalog.py adds the
    # CRM-authenticated download_offer_document route), giving 157.
    # +3 as of FD-2 (foreign-offer development create, rename and assign
    # routes), giving 160.
    # +1 as of FLOOR-2 (foreign-offer manual floor route), giving 161.
    # +1 as of B2B-02A (/dla-biznesu public landing), giving 162.
    # +1 as of SYNC-2C2 (foreign-offer manual field edit route), giving 163.
    # +1 as of FOREIGN-SYNC-UI-1 (foreign source sync action), so the current
    # baseline is 164. 96114e5 intentionally adds the GET offer description
    # route (165); 1fc3bf8 adds manual foreign offer activation (166).
    rules = list(app.url_map.iter_rules())
    # IDB-INT-003 adds one master-only preparation route, without transport.
    # IDB-INT-004 adds list/detail/verify diagnostics, still no transport.
    # INV-01 adds two explicit master-only domestic batch endpoints.
    # +1 master-only, read-only foreign artifact download.
    # +2 master-only scheduler status/settings routes; neither executes jobs.
    # +6 master-only export job routes (Stage 2B: list, create, get, events, cancel, ack-recovery) and
    # +2 read-only panel projections (Stage 3: units, status); none executes delivery.
    assert len(rules) == 193  # Scheduler adds two read-only history routes; S3 adds the description preview route.
    scheduler_rules = [rule for rule in rules if rule.rule == '/crm/scheduled-jobs']
    assert {(rule.endpoint, tuple(sorted(rule.methods - {'HEAD', 'OPTIONS'}))) for rule in scheduler_rules} == {
        ('investmentmanager.scheduled_jobs_status', ('GET',)),
        ('investmentmanager.scheduled_jobs_configure', ('POST',)),
    }
    signatures = [(rule.rule, tuple(sorted(rule.methods))) for rule in rules]
    assert len(signatures) == len(set(signatures)), "Duplicate route registration"
    # The export job collection shares one path between its list (GET) and create (POST) views.
    assert {(rule.endpoint, tuple(sorted(rule.methods - {'HEAD', 'OPTIONS'})))
            for rule in rules if rule.rule == '/crm/offers/export-jobs'} == {
        ('investmentmanager.export_jobs_list', ('GET',)), ('investmentmanager.export_jobs_create', ('POST',))}
    # These are the intentional additions since the old 161 baseline;
    # check endpoint identities and methods, not just the resulting count.
    for path, endpoint, method in (
        ("/crm/offers/export-jobs/units", "investmentmanager.export_jobs_units", "GET"),
        ("/crm/offers/export-jobs/status", "investmentmanager.export_jobs_status", "GET"),
        ("/crm/offers/export-jobs/<job_id>", "investmentmanager.export_jobs_get", "GET"),
        ("/crm/offers/export-jobs/<job_id>/events", "investmentmanager.export_jobs_events", "GET"),
        ("/crm/offers/export-jobs/<job_id>/cancel", "investmentmanager.export_jobs_cancel", "POST"),
        ("/crm/offers/export-jobs/ack-recovery", "investmentmanager.export_jobs_ack_recovery", "POST"),
        ("/crm/offers/export-jobs/attempts/<attempt_id>/resolution-info", "investmentmanager.export_attempt_resolution_info", "GET"),
        ("/crm/offers/export-jobs/attempts/<attempt_id>/resolve", "investmentmanager.export_attempt_resolve", "POST"),
        ("/crm/scheduled-jobs/history", "investmentmanager.scheduled_jobs_history", "GET"),
        ("/crm/scheduled-jobs/history/<string:run_id>", "investmentmanager.scheduled_jobs_log", "GET"),
        ("/crm/offers/export-packages/<string:package_id>/download", "investmentmanager.export_foreign_package_download", "GET"),
        ("/crm/offers/export-packages/foreign-batch/plan", "investmentmanager.foreign_batch_plan", "POST"),
        ("/crm/offers/export-packages/foreign-batch/unit", "investmentmanager.foreign_batch_unit", "POST"),
        ("/crm/offers/export-packages/domestic-batch/plan", "investmentmanager.domestic_batch_plan", "POST"),
        ("/crm/offers/export-packages/domestic-batch/<int:offer_id>", "investmentmanager.domestic_batch_offer", "POST"),
        ("/crm/offers/export-packages/sets/<int:offer_id>/<string:action>/verify", "investmentmanager.export_package_set_verify", "POST"),
        ("/crm/offers/export-packages/sets/<int:offer_id>/<string:action>/cleanup", "investmentmanager.export_package_set_cleanup", "POST"),
        ("/crm/offers/export-packages/foreign/prepare", "investmentmanager.export_foreign_package_prepare", "POST"),
        ("/crm/offers/export-packages", "investmentmanager.export_packages_list", "GET"),
        ("/crm/offers/export-packages/<string:package_id>", "investmentmanager.export_packages_details", "GET"),
        ("/crm/offers/export-packages/<string:package_id>/verify", "investmentmanager.export_packages_verify", "POST"),
        ("/crm/offers/<int:offer_id>/export-package", "investmentmanager.prepare_domestic_export_package", "POST"),
        ("/dla-biznesu", "investment.business_solutions_page", "GET"),
        ("/crm/foreign-offers/<int:foreign_offer_id>/fields", "investmentmanager.foreign_offers_update_fields_api", "POST"),
        ("/crm/foreign-offers/sync/<source_platform>", "investmentmanager.foreign_offers_sync_source_api", "POST"),
        ("/crm/offers/description/<int:offer_id>", "investmentmanager.get_offer_description", "GET"),
        ("/crm/foreign-offers/<int:foreign_offer_id>/active", "investmentmanager.foreign_offers_set_active_api", "POST"),
    ):
        matches = [rule for rule in rules if rule.rule == path]
        assert len(matches) == 1
        assert matches[0].endpoint == endpoint
        assert matches[0].methods - {"OPTIONS", "HEAD"} == {method}


def test_public_homepage_still_serves(legacy_homepage_client):
    resp = legacy_homepage_client.get("/")
    assert resp.status_code == 200


def test_crm_login_page_still_registers(client):
    resp = client.get("/crm/")
    assert resp.status_code == 200


# ---------------------------------------------------------------------------
# Legacy export routes are gone.
# ---------------------------------------------------------------------------

def test_legacy_package_route_no_longer_registered(client):
    resp = client.post("/crm/integrator/portals/no/offers/1/package", json={"mode": "add"})
    assert resp.status_code == 404


def test_legacy_upload_route_no_longer_registered(client):
    resp = client.post("/crm/integrator/portals/no/offers/1/upload", json={"mode": "add"})
    assert resp.status_code == 404


def test_integrator_routes_module_no_longer_exists():
    integrator_routes_path = REPO_ROOT / "InvestmentManager" / "routes" / "integrator.py"
    assert not integrator_routes_path.exists()


# ---------------------------------------------------------------------------
# ACTIVE shared functionality: portal sync state (used by the offer catalog
# "pill" toggle) must still be importable and working.
# ---------------------------------------------------------------------------

def test_portal_sync_state_module_is_importable():
    from InvestmentManager.integrator import portal_sync_state

    assert hasattr(portal_sync_state, "mark_offer_requires_update")
    assert hasattr(portal_sync_state, "ensure_offer_sync_defaults")
    assert hasattr(portal_sync_state, "set_offer_portal_sync_state")


def test_export_only_logging_functions_were_removed_as_orphaned():
    from InvestmentManager.integrator import portal_sync_state

    # Their only caller was the deleted routes/integrator.py upload route.
    assert not hasattr(portal_sync_state, "log_portal_upload_success")
    assert not hasattr(portal_sync_state, "log_portal_upload_failure")


def test_set_offer_portal_sync_state_rejects_invalid_portal_without_db_access():
    from InvestmentManager.integrator.portal_sync_state import set_offer_portal_sync_state

    with pytest.raises(ValueError, match="Nieprawidlowy portal"):
        set_offer_portal_sync_state(offer_id=1, portal_key="not-a-real-portal", state="published")


def test_set_offer_portal_sync_state_rejects_invalid_state_without_db_access():
    from InvestmentManager.integrator.portal_sync_state import set_offer_portal_sync_state

    with pytest.raises(ValueError, match="Nieprawidlowy stan"):
        set_offer_portal_sync_state(offer_id=1, portal_key="no", state="not-a-real-state")


# ---------------------------------------------------------------------------
# ACTIVE shared functionality: Otodom dictionaries (used by offer forms)
# must still be importable and working, with no real HTTP call here.
# ---------------------------------------------------------------------------

def test_otodom_dictionaries_module_is_importable():
    from InvestmentManager.integrator.portals.otodom import dictionaries

    assert hasattr(dictionaries, "fetch_otodom_dictionaries")
    assert hasattr(dictionaries, "map_otodom_code")


def test_otodom_dictionaries_fetch_uses_urllib_without_real_network(monkeypatch):
    from InvestmentManager.integrator.portals.otodom import dictionaries

    dictionaries._CACHE["data"] = None
    dictionaries._CACHE["expires_at"] = 0.0

    calls = []

    class _FakeResponse:
        def __enter__(self):
            return self

        def __exit__(self, *exc_info):
            return False

        def read(self):
            import json
            return json.dumps({"dictionaries": {"section": {"key": ["A", "B"]}}}).encode("utf-8")

    def fake_urlopen(url, timeout=None):
        calls.append(url)
        return _FakeResponse()

    monkeypatch.setattr(dictionaries.urllib.request, "urlopen", fake_urlopen)
    monkeypatch.setattr(dictionaries.json, "load", lambda response: {"dictionaries": {"section": {"key": ["A", "B"]}}})

    result = dictionaries.fetch_otodom_dictionaries()
    assert calls == [dictionaries.OTODOM_DICTIONARIES_URL]
    assert result == {"section": {"key": ["A", "B"]}}


def test_no_export_engine_package_left_under_portals():
    portals_dir = REPO_ROOT / "InvestmentManager" / "integrator" / "portals"
    remaining = sorted(p.name for p in portals_dir.iterdir() if p.name != "__pycache__")
    # Only the shared, active Otodom dictionaries submodule (plus its own
    # package __init__.py) and this package's own __init__.py should remain.
    assert remaining == ["__init__.py", "otodom"]

    otodom_dir = portals_dir / "otodom"
    remaining_otodom = sorted(p.name for p in otodom_dir.iterdir() if p.name != "__pycache__")
    assert remaining_otodom == ["__init__.py", "dictionaries.py"]


# ---------------------------------------------------------------------------
# No leftover FTP_*/INTEGRATOR_DOTENV_FILE/IMAGES_BASE_PATH consumers.
# ---------------------------------------------------------------------------

_ENV_VAR_PATTERN = re.compile(r"FTP_[A-Z_]+|INTEGRATOR_DOTENV_FILE|IMAGES_BASE_PATH")

_SCAN_DIRS = ("InvestmentManager", "InvestmentWebsite", "modules", "blueprints", "middleware")
_EXCLUDE_DIR_NAMES = {"__pycache__"}


def _iter_python_files():
    for dirname in _SCAN_DIRS:
        base = REPO_ROOT / dirname
        if not base.exists():
            continue
        for path in base.rglob("*.py"):
            if any(part in _EXCLUDE_DIR_NAMES for part in path.parts):
                continue
            yield path


# Stage 2B transport adapters deliberately own the five FTP profile key names (D07).
_STAGE_2B_TRANSPORT = {"export_transport_config.py", "portal_transport.py"}


def test_no_remaining_ftp_or_integrator_env_var_references_in_source():
    offenders = []
    for path in _iter_python_files():
        if path.name in _STAGE_2B_TRANSPORT and path.parent.name == "integrator":
            continue
        text = path.read_text(encoding="utf-8", errors="ignore")
        if _ENV_VAR_PATTERN.search(text):
            offenders.append(str(path.relative_to(REPO_ROOT)))

    assert offenders == []


def test_env_example_has_no_legacy_integrator_override_entries_and_only_executor_ftp_keys():
    env_example = REPO_ROOT / ".env.example"
    text = env_example.read_text(encoding="utf-8")
    # The legacy engine overrides must never come back.
    assert not re.search(r"INTEGRATOR_DOTENV_FILE|IMAGES_BASE_PATH", text)
    # Since 2026-11 the CRM is the only export operator: its executor reads FTP_<PROFILE>_* from .env. The example may list exactly
    # those keys (with empty values) and nothing else that looks like an FTP setting (e.g. the inactive Otodom profile).
    from InvestmentManager.integrator import export_transport_config as config
    listed = set(re.findall(r"^\s*#?\s*(FTP_[A-Z_]+)=", text, re.M))
    assert listed <= set(config.ALLOWED_KEYS), sorted(listed - set(config.ALLOWED_KEYS))
    assert all(not value.strip() for value in re.findall(r"^\s*FTP_[A-Z_]+=(.*)$", text, re.M))
    # DB_SHELL_PASSWORD is unrelated to the export engine and must remain.
    assert "DB_SHELL_PASSWORD" in text
