import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'packages' / 'agromatrix-tools'))

from agromatrix_tools import tool_operation_plan as op


def test_create_plan():
    plan_id = op.create_plan({
        'scope': {'field_ids': ['field_001'], 'crop_ids': ['crop_wheat_winter'], 'date_window': {'start': '2026-02-08', 'end': '2026-02-15'}},
        'tasks': [{'operation_id': 'op_sowing', 'planned_date': '2026-02-10', 'priority': 'normal', 'assignee': 'team'}]
    }, trace_id='t1')
    assert plan_id
    plan = op.get_plan(plan_id)
    assert plan['status'] == 'planned'


def test_update_and_status():
    plan_id = op.create_plan({'scope': {'field_ids': ['field_001'], 'crop_ids': [], 'date_window': {'start':'2026-02-08','end':'2026-02-10'}}, 'tasks': []}, trace_id='t2')
    op.update_plan(plan_id, {'source': 'api'})
    op.set_status(plan_id, 'scheduled')
    plan = op.get_plan(plan_id)
    assert plan['status'] == 'scheduled'


def test_invalid_transition():
    plan_id = op.create_plan({'scope': {'field_ids': ['field_001'], 'crop_ids': [], 'date_window': {'start':'2026-02-08','end':'2026-02-10'}}, 'tasks': []}, trace_id='t3')
    try:
        op.set_status(plan_id, 'closed')
        assert False, 'should have failed'
    except Exception:
        assert True
