from datetime import date
from pathlib import Path
from unittest.mock import MagicMock

import httpx
import pytest

from timesheet import rmbdb, rmbimages


def test_filters_bind_search_and_validate_date_ranges():
    sql, params = rmbdb.workspace_filter_sql({
        "q": "товар%_'", "overdue": "soon", "created_from": "2026-11-01",
        "created_to": "2026-11-02", "due_to": "2026-11-05"})
    assert "товар" not in sql
    assert params == [date(2026, 11, 1), date(2026, 11, 2), date(2026, 11, 5), "%товар\\%\\_'%"]
    assert "current_date+3" in sql
    with pytest.raises(ValueError):
        rmbdb.workspace_filter_sql({"created_from": "2026-11-02", "created_to": "2026-11-01"})
    with pytest.raises(ValueError):
        rmbdb.workspace_filter_sql({"due_from": "2026-02-30"})
    with pytest.raises(ValueError):
        rmbdb.workspace_filter_sql({"overdue": "unknown"})


def test_product_code_comes_from_unit_key():
    assert rmbdb.product_code("10142911-БК-2585436") == "10142911"
    assert rmbdb.product_code(None) == ""
    assert rmbdb.product_code("not-a-code") == ""


def payload(code="10.142.911", image="https://cdn21vek.by/photo.png"):
    return {"data": [{"group_type": "products", "items": [{"product_id": code, "image": image}]}]}


def test_photo_requires_exact_code_and_trusted_image_host():
    assert rmbimages.find_image(payload(), "10142911") == "https://cdn21vek.by/photo.png"
    assert rmbimages.find_image(payload("10.142.912"), "10142911") is None
    assert rmbimages.find_image(payload(image="https://cdn21vek.by.evil.test/photo"), "10142911") is None
    assert rmbimages.find_image(payload(image="http://127.0.0.1/photo"), "10142911") is None


def test_photo_bytes_are_cached_and_reused_without_network(tmp_path, monkeypatch):
    requests = []
    def respond(request):
        requests.append(str(request.url))
        if request.url.host == "gate.21vek.by":
            return httpx.Response(200, json=payload())
        return httpx.Response(200, content=b"photo-bytes", headers={"content-type": "image/png"})
    client = httpx.Client
    monkeypatch.setattr(rmbimages.httpx, "Client", lambda **kw: client(transport=httpx.MockTransport(respond), **kw))
    path, mime = rmbimages.cached_photo(tmp_path, "10142911")
    assert path.read_bytes() == b"photo-bytes" and mime == "image/png"
    assert rmbimages.cached_photo(tmp_path, "10142911") == (path, mime)
    assert len(requests) == 2
    with pytest.raises(ValueError):
        rmbimages.cached_photo(tmp_path, "../secret")


def test_missing_photo_is_cached_temporarily(tmp_path, monkeypatch):
    requests = []
    def respond(request):
        requests.append(request)
        return httpx.Response(200, json=payload("999"))
    client = httpx.Client
    monkeypatch.setattr(rmbimages.httpx, "Client", lambda **kw: client(transport=httpx.MockTransport(respond), **kw))
    assert rmbimages.cached_photo(tmp_path, "10142911") is None
    assert rmbimages.cached_photo(tmp_path, "10142911") is None
    assert len(requests) == 1


def test_history_denies_invisible_case_before_reading_events(monkeypatch):
    monkeypatch.setattr(rmbdb, "_visible_rows", lambda *a, **kw: [])
    with pytest.raises(PermissionError):
        rmbdb.case_history(None, 1, "manager", 99)


def test_claim_and_start_does_not_commit_until_both_operations_succeed(monkeypatch):
    conn = MagicMock()
    claim = MagicMock()
    monkeypatch.setattr(rmbdb, "claim_task", claim)
    monkeypatch.setattr(rmbdb, "_owned_task", lambda *a: {
        "task_status": "claimed", "case_id": 10, "direction": "sorting"})
    rmbdb.task_action(conn, 3, 7, "claim_start", commit=False)
    claim.assert_called_once_with(conn, 3, 7, commit=False)
    conn.commit.assert_not_called()
    monkeypatch.setattr(rmbdb, "_owned_task", lambda *a: {
        "task_status": "completed", "case_id": 10, "direction": "sorting"})
    with pytest.raises(ValueError):
        rmbdb.task_action(conn, 3, 7, "claim_start")
    conn.commit.assert_not_called()
