from pathlib import Path

from flask import Blueprint, Flask, jsonify


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


def _metrics_app() -> Flask:
    from services.http_access_policy_service import enforce_http_access_policy

    app = Flask(__name__)
    system_public = Blueprint("system_public", __name__)

    @system_public.route("/metrics")
    def prometheus_metrics():
        return jsonify({"status": "up"})

    app.register_blueprint(system_public)
    app.before_request(enforce_http_access_policy)
    return app


def test_metrics_network_classifier_is_deny_by_default():
    from services.http_access_policy_service import is_internal_metrics_request

    assert is_internal_metrics_request("127.0.0.1") is True
    assert is_internal_metrics_request("172.20.0.4") is True
    assert is_internal_metrics_request("127.0.0.1", "172.20.0.4") is True
    assert is_internal_metrics_request("127.0.0.1", "203.0.113.10") is False
    assert is_internal_metrics_request("127.0.0.1", "192.168.0.110") is True
    assert is_internal_metrics_request("127.0.0.1", "192.168.0.111") is False
    assert is_internal_metrics_request("203.0.113.10", "172.20.0.4") is False
    assert is_internal_metrics_request("127.0.0.1", "not-an-ip") is False


def test_metrics_route_denies_public_and_lan_but_allows_internal_transport():
    client = _metrics_app().test_client()

    public = client.get(
        "/metrics",
        environ_base={"REMOTE_ADDR": "127.0.0.1"},
        headers={"X-Real-IP": "203.0.113.10"},
    )
    lan = client.get(
        "/metrics",
        environ_base={"REMOTE_ADDR": "127.0.0.1"},
        headers={"X-Real-IP": "192.168.0.111"},
    )
    internal = client.get(
        "/metrics",
        environ_base={"REMOTE_ADDR": "127.0.0.1"},
        headers={"X-Real-IP": "172.20.0.4"},
    )
    monitoring = client.get(
        "/metrics",
        environ_base={"REMOTE_ADDR": "127.0.0.1"},
        headers={"X-Real-IP": "192.168.0.110"},
    )
    direct = client.get("/metrics", environ_base={"REMOTE_ADDR": "172.18.0.5"})

    assert public.status_code == 404
    assert public.get_json() == {"error": "not_found"}
    assert lan.status_code == 404
    assert internal.status_code == 200
    assert monitoring.status_code == 200
    assert direct.status_code == 200


def test_source_owned_edge_and_prometheus_templates_are_closed_by_default():
    nginx = (ROOT / "monitoring/edge/ewoooc_metrics_nginx_bridge.conf").read_text(
        encoding="utf-8"
    )
    prometheus = (ROOT / "monitoring/edge/ewoooc_prometheus_scrape.yml").read_text(
        encoding="utf-8"
    )

    assert "listen 172.20.0.1:19191;" in nginx
    assert "location = /metrics" in nginx
    assert "allow 127.0.0.1;" in nginx
    assert "allow 172.16.0.0/12;" in nginx
    assert "allow 192.168.0.110/32;" in nginx
    assert "deny all;" in nginx
    assert "proxy_pass https://192.168.0.188/metrics;" in nginx
    assert "proxy_ssl_verify on;" in nginx
    assert "job_name: 'ewoooc-app'" in prometheus
    assert "metrics_path: /metrics" in prometheus
    assert "targets: ['172.20.0.1:19191']" in prometheus


def test_monitoring_compose_has_no_plaintext_admin_password_or_public_prometheus_port():
    compose = (ROOT / "monitoring/docker-compose.yml").read_text(encoding="utf-8")

    assert "GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_ADMIN_PASSWORD:?" in compose
    assert "127.0.0.1:9090:9090" in compose
    assert "\n      - \"9090:9090\"" not in compose
