"""Tests that verify formula evaluation works end-to-end."""

import pytest

from ironcalc_mcp.state import workbook


def test_simple_arithmetic():
    workbook.set_cell(0, 1, 1, "=2+3")
    cell = workbook.get_cell(0, 1, 1)
    assert cell.formatted == "5"
    assert cell.cell_type == "number"


def test_sum_range():
    workbook.set_cell(0, 1, 1, "10")
    workbook.set_cell(0, 2, 1, "20")
    workbook.set_cell(0, 3, 1, "30")
    workbook.set_cell(0, 4, 1, "=SUM(A1:A3)")
    cell = workbook.get_cell(0, 4, 1)
    assert cell.formatted == "60"


def test_string_concat():
    workbook.set_cell(0, 1, 1, "Hello")
    workbook.set_cell(0, 1, 2, '=A1&" World"')
    cell = workbook.get_cell(0, 1, 2)
    assert cell.formatted == "Hello World"
    assert cell.cell_type == "text"


def test_cross_sheet_reference():
    workbook.model.add_sheet("Sheet2")
    workbook.model.evaluate()
    workbook.set_cell(0, 1, 1, "42")
    workbook.set_cell(1, 1, 1, "=Sheet1!A1*2")
    cell = workbook.get_cell(1, 1, 1)
    assert cell.formatted == "84"


def test_cell_types():
    workbook.set_cell(0, 1, 1, "hello")
    workbook.set_cell(0, 2, 1, "42")
    workbook.set_cell(0, 3, 1, "=1/0")

    assert workbook.get_cell(0, 1, 1).cell_type == "text"
    assert workbook.get_cell(0, 2, 1).cell_type == "number"
    assert workbook.get_cell(0, 3, 1).cell_type == "errorvalue"


def test_batch_set_and_read():
    cells = [
        {"sheet": 0, "row": r, "column": 1, "value": str(r)}
        for r in range(1, 11)
    ]
    workbook.set_cells_batch(cells)
    result = workbook.get_cells_in_range(0, 1, 1, 10, 1)
    assert len(result) == 10
    assert result[0].formatted == "1"
    assert result[9].formatted == "10"
