from datetime import date
from pathlib import Path

import pytest
import requests

from InvestmentManager import matomo_reporting
from InvestmentManager.matomo_reporting import MatomoReportingUnavailable
from InvestmentManager.routes import statistics
from tests.investmentmanager.conftest import CRM_ANN, CRM_ANN_OFFER, CRM_BOB_OFFER, CRM_MASTER


class _Response:
    status_code = 200

    def __init__(self, payload):
        self._payload = payload

    def json(self):
        return self._payload


@pytest.fixture(autouse=True)
def _empty_reporting_cache():
    matomo_reporting.clear_cache()
    yield
    matomo_reporting.clear_cache()


def _config(**overrides):
    config = {
        "MATOMO_REPORTING_ENABLED": True,
        "MATOMO_BASE_URL": "https://analytics.example.invalid/",
        "MATOMO_SITE_ID": 1,
        "MATOMO_OFFER_DIMENSION_ID": 2,
        "MATOMO_REPORTING_START_DATE": "2026-11-01",
    }
    config.update(overrides)
    return config


def test_reporting_is_fail_closed_until_explicitly_configured(monkeypatch):
    called = False

    def unexpected_request(*args, **kwargs):
        nonlocal called
        called = True

    monkeypatch.setattr(matomo_reporting.requests, "post", unexpected_request)
    monkeypatch.setattr(matomo_reporting, "matomo_reporting_token", lambda: "")

    with pytest.raises(MatomoReportingUnavailable) as exc_info:
        matomo_reporting.offer_pageviews(
            _config(MATOMO_REPORTING_ENABLED=False),
            "offer:v1:investment:501",
            "last_3_months",
        )

    assert exc_info.value.code == "matomo_not_configured"
    assert called is False


def test_bulk_daily_report_is_cached_and_token_stays_in_post_body(monkeypatch):
    calls = []

    def fake_post(url, **kwargs):
        calls.append((url, kwargs))
        return _Response({
            "2026-11-20": [
                {"label": "offer:v1:investment:501", "nb_hits": 3},
                {"label": "offer:v1:investment:601", "nb_hits": "5"},
            ],
            "2026-11-21": [{"label": "offer:v1:investment:501", "nb_hits": 2}],
        })

    monkeypatch.setattr(matomo_reporting.requests, "post", fake_post)
    monkeypatch.setattr(matomo_reporting, "matomo_reporting_token", lambda: "server-secret")

    first = matomo_reporting.offer_pageviews(
        _config(), "offer:v1:investment:501", "last_3_months", today=date(2026, 11, 21)
    )
    second = matomo_reporting.offer_pageviews(
        _config(), "offer:v1:investment:601", "last_3_months", today=date(2026, 11, 21)
    )

    assert first["total_views"] == 5
    assert first["series_daily"] == [
        {"date": "2026-11-20", "views": 3},
        {"date": "2026-11-21", "views": 2},
    ]
    assert second["total_views"] == 5
    assert second["cache_hit"] is True
    assert len(calls) == 1
    url, kwargs = calls[0]
    assert url == "https://analytics.example.invalid/index.php"
    assert "server-secret" not in url
    assert kwargs["data"]["token_auth"] == "server-secret"
    assert kwargs["data"]["method"] == "CustomDimensions.getCustomDimension"
    assert kwargs["data"]["period"] == "day"
    assert kwargs["allow_redirects"] is False


def test_unavailable_matomo_returns_stale_cache_not_a_fabricated_zero(monkeypatch):
    responses = [
        _Response({"2026-11-21": [{"label": "offer:v1:investment:501", "nb_hits": 7}]}),
        requests.ConnectionError("offline"),
    ]

    def fake_post(*args, **kwargs):
        result = responses.pop(0)
        if isinstance(result, Exception):
            raise result
        return result

    monkeypatch.setattr(matomo_reporting.requests, "post", fake_post)
    monkeypatch.setattr(matomo_reporting, "matomo_reporting_token", lambda: "server-secret")
    monkeypatch.setattr(matomo_reporting, "_CACHE_TTL_SECONDS", 0)

    first = matomo_reporting.offer_pageviews(
        _config(), "offer:v1:investment:501", "current_year", today=date(2026, 11, 21)
    )
    stale = matomo_reporting.offer_pageviews(
        _config(), "offer:v1:investment:501", "current_year", today=date(2026, 11, 21)
    )

    assert first["total_views"] == 7
    assert stale["total_views"] == 7
    assert stale["stale"] is True


def test_offer_endpoint_preserves_acl_and_has_no_unique_user_metric(app, crm_env, crm_login, monkeypatch):
    monkeypatch.setattr(statistics, "offer_pageviews", lambda config, key, range_name: {
        "data_available": True,
        "source": "matomo",
        "metric": "pageviews",
        "series_daily": [],
        "series_cumulative": [],
        "total_views": 4,
    })
    ann = crm_login(app, CRM_ANN)
    own = ann.get(f"/crm/statistics/offer/{CRM_ANN_OFFER}")
    assert own.status_code == 200
    assert own.get_json()["total_views"] == 4
    assert "unique_users" not in own.get_json()
    assert ann.get(f"/crm/statistics/offer/{CRM_BOB_OFFER}").status_code == 403
    assert ann.get("/crm/statistics/offer/999999").status_code == 404

    master = crm_login(app, CRM_MASTER)
    assert master.get(f"/crm/statistics/offer/{CRM_BOB_OFFER}").status_code == 200


def test_offer_endpoint_reports_no_data_instead_of_zero_when_matomo_is_unavailable(
    app, crm_env, crm_login, monkeypatch
):
    def unavailable(*args, **kwargs):
        raise MatomoReportingUnavailable("offline")

    monkeypatch.setattr(statistics, "offer_pageviews", unavailable)
    response = crm_login(app, CRM_ANN).get(f"/crm/statistics/offer/{CRM_ANN_OFFER}")
    payload = response.get_json()

    assert response.status_code == 503
    assert payload["data_available"] is False
    assert "total_views" not in payload


def test_legacy_site_wide_traffic_endpoint_is_removed(app):
    assert app.test_client().get("/crm/statistics").status_code == 404


def test_offer_cards_no_longer_claims_an_ip_user_agent_unique_user_metric():
    source = Path(matomo_reporting.__file__).parent / "static" / "js" / "offers_cards.js"
    text = source.read_text(encoding="utf-8")
    assert "unique_users" not in text
    assert "Unikalni użytkownicy" not in text


def test_public_blueprints_no_longer_emit_catalog_or_offer_view_events():
    root = Path(matomo_reporting.__file__).parents[1] / "InvestmentWebsite" / "blueprints"
    sources = "\n".join(
        (root / relative).read_text(encoding="utf-8-sig")
        for relative in (
            "tripinvest/tripinvest.py",
            "avarten/avarten.py",
            "homelanzarote/lanzarote.py",
        )
    )
    assert 'event="catalog_view"' not in sources
    assert 'event="offer_page_view"' not in sources
    assert 'channel="traffic"' not in sources
