"""The SEO CLI shares application paths and never selects a historical backup."""
import hashlib
import importlib.util
from pathlib import Path
import sqlite3

from flask import Flask, Response, request
import pytest

from modules.core import storage_paths


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


@pytest.fixture
def smoke():
    spec = importlib.util.spec_from_file_location("seo_smoke_c4", ROOT / "tools/qa/seo_smoke.py")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    assert module.PROJECT_ROOT == ROOT
    return module


def _database(path):
    path.parent.mkdir(parents=True, exist_ok=True)
    with sqlite3.connect(path) as conn:
        conn.execute("CREATE TABLE EstateData (ID INTEGER, Typ_nieruchomosci TEXT, "
                     "Typ_oferty TEXT, Liczba_pokoi INTEGER, Miejscowosc TEXT, Status_oferty TEXT)")
        conn.executemany("INSERT INTO EstateData VALUES (?, ?, ?, ?, ?, ?)", [
            (2, "mieszkanie", "sprzedaz", 2, "Test", "aktywna"),
            (4, "mieszkanie", "sprzedaz", 3, "Test", "aktywna"),
            (9, "dom", "sprzedaz", 5, "Test", "nieaktywna"),
        ])


@pytest.mark.parametrize("mode", ["explicit", "sibling", "legacy", "explicit_over_legacy"])
def test_selection_matches_application_resolver_from_foreign_cwd(smoke, monkeypatch, tmp_path, mode):
    checkout = tmp_path / "checkout"
    monkeypatch.setattr(storage_paths, "REPO_ROOT", checkout)
    monkeypatch.delenv("DATA_DIR", raising=False)
    monkeypatch.delenv("INVESTMENT_LEGACY_STORAGE", raising=False)
    if mode.startswith("explicit"):
        monkeypatch.setenv("DATA_DIR", str(tmp_path / "external data # fixture"))
    if mode in {"legacy", "explicit_over_legacy"}:
        monkeypatch.setenv("INVESTMENT_LEGACY_STORAGE", "1")
    expected = (tmp_path / "external data # fixture/databases/IDB.db" if mode.startswith("explicit")
                else checkout / "instances/IDB.db" if mode == "legacy"
                else tmp_path / "InvestmentData/databases/IDB.db")
    assert storage_paths.idb_db_path() == expected
    _database(expected)
    before = hashlib.sha256(expected.read_bytes()).hexdigest()
    foreign_cwd = tmp_path / "different-cwd"
    foreign_cwd.mkdir()
    monkeypatch.chdir(foreign_cwd)
    assert smoke._find_active_offer_row() == (4, "mieszkanie", "sprzedaz", 3, "Test")
    assert hashlib.sha256(expected.read_bytes()).hexdigest() == before
    assert not list(foreign_cwd.iterdir())


def test_missing_database_is_not_created_and_cwd_backups_are_ignored(smoke, monkeypatch, tmp_path):
    monkeypatch.setenv("DATA_DIR", str(tmp_path / "missing-data"))
    monkeypatch.chdir(tmp_path)
    _database(tmp_path / "instances/IDB.db")
    _database(tmp_path / "instances/backup/IDB_20260303_194052.db")
    assert smoke._find_active_offer_row() is None
    assert not (tmp_path / "missing-data").exists()


def test_relative_data_dir_is_rejected_by_existing_resolver(smoke, monkeypatch):
    monkeypatch.setenv("DATA_DIR", "relative-data")
    with pytest.raises(ValueError, match="must be an absolute path"):
        smoke._find_active_offer_row()


def test_connection_is_read_only_query_only_and_closed(smoke, monkeypatch, tmp_path):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    path = storage_paths.idb_db_path()
    _database(path)
    connect = sqlite3.connect
    opened = []
    traces = []

    def checked_connect(database_uri, **kwargs):
        assert database_uri == path.resolve().as_uri() + "?mode=ro"
        assert kwargs == {"uri": True}
        conn = connect(database_uri, **kwargs)
        with pytest.raises(sqlite3.OperationalError, match="readonly"):
            conn.execute("DELETE FROM EstateData")
        opened.append(conn)
        conn.set_trace_callback(traces.append)
        return conn

    monkeypatch.setattr(smoke.sqlite3, "connect", checked_connect)
    assert smoke._find_active_offer_row()[0] == 4
    assert "PRAGMA query_only=ON" in traces
    assert len(opened) == 1
    with pytest.raises(sqlite3.ProgrammingError, match="closed"):
        opened[0].execute("SELECT 1")


def test_corrupt_database_warns_without_fallback_or_path_disclosure(smoke, monkeypatch, tmp_path, capsys):
    monkeypatch.setenv("DATA_DIR", str(tmp_path / "private-data"))
    path = storage_paths.idb_db_path()
    path.parent.mkdir(parents=True)
    path.write_bytes(b"not a SQLite database")
    before = path.read_bytes()
    monkeypatch.chdir(tmp_path)
    _database(tmp_path / "instances/backup/IDB_20260303_194052.db")
    assert smoke._find_active_offer_row() is None
    output = capsys.readouterr().out
    assert "Cannot read the configured database" in output
    assert str(path) not in output
    assert path.read_bytes() == before


def _seo_site(smoke, visited):
    app = Flask(__name__)

    @app.route("/", defaults={"path": ""})
    @app.route("/<path:path>")
    def page(path):
        url = request.full_path.rstrip("?")
        visited.append(url)
        if request.path == "/sitemap.xml":
            return Response("<urlset><url><lastmod>2026-01-01</lastmod>"
                            "<changefreq>daily</changefreq><priority>1</priority>"
                            "<loc>https://investment-nieruchomosci.com/nieruchomosci</loc></url></urlset>",
                            mimetype="application/xml")
        policy = next((p for p in smoke.NOINDEX_URLS if p["url"] == url), None)
        robots = f'<meta name="robots" content="{policy["meta_robots"]}">' if policy and policy["meta_robots"] else ""
        response = Response(f'<title>{request.path}</title><meta name="description" content="fixture">'
                            f'<link rel="canonical" href="{request.host_url.rstrip("/")}{request.path}">{robots}')
        if policy:
            response.headers["X-Robots-Tag"] = policy["x_robots"]
        return response

    return app


@pytest.mark.parametrize("skip_offer", [False, True])
def test_full_smoke_scope_runs_in_process_on_synthetic_data(smoke, monkeypatch, tmp_path, capsys, skip_offer):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    _database(storage_paths.idb_db_path())
    visited = []
    app = _seo_site(smoke, visited)
    monkeypatch.setattr(smoke, "create_app", lambda: app)
    assert smoke.run_smoke(skip_offer=skip_offer, base_url="http://seo-fixture.test") == 0
    expected = list(smoke.INDEXABLE_URLS)
    if not skip_offer:
        expected.append(smoke.build_offer_path(offer_id=4, property_type="mieszkanie",
                                             offer_type="sprzedaz", rooms=3, city="Test"))
    expected += [p["url"] for p in smoke.NOINDEX_URLS] + ["/sitemap.xml"]
    assert visited == expected
    assert "[RESULT] PASS" in capsys.readouterr().out


def test_smoke_still_rejects_wrong_canonical(smoke, monkeypatch, capsys):
    app = _seo_site(smoke, [])

    @app.after_request
    def wrong_canonical(response):
        response.set_data(response.get_data().replace(b'http://seo-fixture.test/', b'http://wrong.test/'))
        return response

    monkeypatch.setattr(smoke, "create_app", lambda: app)
    assert smoke.run_smoke(skip_offer=True, base_url="http://seo-fixture.test") == 1
    assert "canonical matches expected" in capsys.readouterr().out
