import json
import os
import subprocess
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from orderdesk.app import grand_total, order_total  # noqa: E402


def test_no_discount_total():
    order = {"order_id": "A1", "customer": "Acme",
             "line_items": [{"qty": 2, "unit_price": 10.00}]}
    assert order_total(order) == 21.75  # 20 * 1.0875


def test_grand_total_two_orders():
    o = {"order_id": "A1", "customer": "Acme",
         "line_items": [{"qty": 1, "unit_price": 100.00}]}
    assert grand_total([o, o]) == 217.50


def test_export_runs(tmp_path):
    orders = [{"order_id": "A1", "customer": "Acme",
               "line_items": [{"qty": 1, "unit_price": 5.00}]}]
    src = tmp_path / "orders.json"
    src.write_text(json.dumps(orders))
    out = tmp_path / "out.csv"
    subprocess.run([sys.executable, "-m", "orderdesk.app", "export", str(src), str(out)],
                   check=True, cwd=os.path.join(os.path.dirname(__file__), ".."))
    assert out.read_text().splitlines()[0] == "order_id,customer,total"
