"""Tests for history tracking and diff."""

from __future__ import annotations

import json
from pathlib import Path

import pytest

from sb_scout.history import append_snapshot, diff_snapshots, load_last_snapshot


@pytest.fixture()
def history_file(tmp_path: Path) -> Path:
    return tmp_path / "history.jsonl"


@pytest.fixture()
def sample_rows():
    return [
        {"id": 1, "cpu": "CPU A", "price_amount": 50.0, "ram_gb": 64, "storage_gb": 1000, "score_overall_rank": 0.8},
        {"id": 2, "cpu": "CPU B", "price_amount": 80.0, "ram_gb": 128, "storage_gb": 2000, "score_overall_rank": 0.6},
    ]


class TestAppendSnapshot:
    def test_creates_file(self, history_file, sample_rows):
        append_snapshot(history_file, sample_rows)
        assert history_file.exists()
        lines = history_file.read_text().strip().split("\n")
        assert len(lines) == 1
        snap = json.loads(lines[0])
        assert snap["count"] == 2
        assert len(snap["servers"]) == 2

    def test_appends(self, history_file, sample_rows):
        append_snapshot(history_file, sample_rows)
        append_snapshot(history_file, sample_rows[:1])
        lines = history_file.read_text().strip().split("\n")
        assert len(lines) == 2

    def test_includes_profile(self, history_file, sample_rows):
        append_snapshot(history_file, sample_rows, profile="test")
        snap = json.loads(history_file.read_text().strip())
        assert snap["profile"] == "test"


class TestLoadLastSnapshot:
    def test_no_file(self, tmp_path):
        assert load_last_snapshot(tmp_path / "nope.jsonl") is None

    def test_empty_file(self, history_file):
        history_file.write_text("")
        assert load_last_snapshot(history_file) is None

    def test_returns_last(self, history_file, sample_rows):
        append_snapshot(history_file, sample_rows)
        append_snapshot(history_file, sample_rows[:1])
        snap = load_last_snapshot(history_file)
        assert snap is not None
        assert snap["count"] == 1


class TestDiffSnapshots:
    def test_no_changes(self, sample_rows):
        prev = {"servers": [{"id": r["id"], "price_amount": r["price_amount"]} for r in sample_rows]}
        d = diff_snapshots(prev, sample_rows)
        assert d["new_count"] == 0
        assert d["removed_count"] == 0
        assert d["price_change_count"] == 0

    def test_new_server(self, sample_rows):
        prev = {"servers": [{"id": 1, "price_amount": 50.0}]}
        d = diff_snapshots(prev, sample_rows)
        assert 2 in d["new"]
        assert d["new_count"] == 1

    def test_removed_server(self, sample_rows):
        prev = {"servers": [
            {"id": 1, "price_amount": 50.0},
            {"id": 2, "price_amount": 80.0},
            {"id": 3, "price_amount": 90.0},
        ]}
        d = diff_snapshots(prev, sample_rows)
        assert 3 in d["removed"]
        assert d["removed_count"] == 1

    def test_price_change(self, sample_rows):
        prev = {"servers": [
            {"id": 1, "price_amount": 55.0},
            {"id": 2, "price_amount": 80.0},
        ]}
        d = diff_snapshots(prev, sample_rows)
        assert d["price_change_count"] == 1
        assert d["price_changes"][0]["delta"] == -5.0
