from __future__ import annotations

import pytest
from django.urls import reverse

from rad import logging_setup


def test_loguru_uses_django_file_handler_path(settings, tmp_path, monkeypatch):
    monkeypatch.setattr(logging_setup, "_CONFIGURED", False)
    settings.BASE_DIR = str(tmp_path)
    settings.LOGGING = {
        "handlers": {
            "file": {
                "filename": "log.txt",
            }
        }
    }

    assert logging_setup._get_log_file_path() == tmp_path / "log.txt"


@pytest.mark.django_db
def test_logs_view_filters_by_date_and_can_reset_log_file(client, admin_user, monkeypatch, tmp_path):
    client.force_login(admin_user)

    log_file = tmp_path / "app.log"
    log_file.write_text(
        "[03/Jun/2026 10:00:00] INFO [atlas.views:10] first entry\n"
        "[03/Jun/2026 11:00:00] ERROR [atlas.views:11] second entry\n",
        encoding="utf-8",
    )
    monkeypatch.setattr("rad.views.get_log_file_path", lambda: log_file)

    response = client.get(
        reverse("logs_view"),
        {
            "date_from": "2026-06-03",
            "date_to": "2026-06-03",
            "time_from": "10:30",
            "time_to": "11:30",
        },
    )

    assert response.status_code == 200
    assert b"second entry" in response.content
    assert b"first entry" not in response.content

    response = client.post(reverse("logs_view"), {"action": "clear"})

    assert response.status_code == 200
    assert b"Log file cleared." in response.content
    assert log_file.read_text(encoding="utf-8") == ""