import pytest from gti_fiscal_agent.state import AgentState def test_outbox_keeps_failed_work_pending(tmp_path): state = AgentState(tmp_path / "agent.db") assert state.enqueue("000276", "source", "v1", "0.1.0") state.retry("000276") assert state.pending()[0]["status"] == "PENDING_API" state.result_received("000276", "source", "v1", "0.1.0") assert state.enqueue("000276", "source", "v1", "0.1.0") is False def test_ipi_write_log_records_per_product_audit(tmp_path): state = AgentState(tmp_path / "agent.db") state.log_ipi_write("000276", "fp1", "EXACT_NCM", "IPI_RESOLVED", "SUCCEEDED", None, 3.25, "rowcount=1", "CHANGE_REQUIRED", "2026-09-18T00:00:00Z") log = state.ipi_write_log_for("000276") assert len(log) == 1 assert log[0]["write_status"] == "SUCCEEDED" assert log[0]["before_value"] is None assert log[0]["proposed_value"] == "3.25" def test_installation_identity_requires_an_existing_or_explicit_id(tmp_path): state = AgentState(tmp_path / "agent.db") assert state.stored_installation_id() is None with pytest.raises(ValueError, match="installation_id is required"): state.installation_id() assert state.connection.execute("SELECT COUNT(*) FROM installation_identity").fetchone()[0] == 0 def test_installation_identity_persists_and_reuses_explicit_id(tmp_path): db_path = tmp_path / "agent.db" state = AgentState(db_path) existing_id = "00000000-0000-4000-8000-000000000222" assert state.installation_id(existing_id) == existing_id assert state.installation_id() == existing_id assert state.stored_installation_id() == existing_id restarted_state = AgentState(db_path) assert restarted_state.installation_id() == existing_id def test_installation_identity_rejects_conflicting_or_malformed_ids(tmp_path): state = AgentState(tmp_path / "agent.db") existing_id = "00000000-0000-4000-8000-000000000222" state.installation_id(existing_id) with pytest.raises(ValueError, match="conflicts"): state.installation_id("00000000-0000-4000-8000-000000000223") with pytest.raises(ValueError, match="UUID"): state.installation_id("not-a-uuid")