"""Save id and column mappings and upload the sample POS/ERP files to a running server.

    python -m scripts.load_samples [--style odoo|generic] [--base http://localhost:8000/api/v1]

Needs the demo seed (site codes, SKUs and SUP1/SUP2 must exist) and the SIM clock, and the
outlet should already hold tomatoes and milk for the sales to attach to.
"""
import argparse
import json
from pathlib import Path

import httpx

SAMPLES = Path(__file__).resolve().parents[2] / "samples"
STYLES = {
    "generic": {
        "mappings": "mappings.json",
        "ids": [],
        "uploads": [("erp", "product", "erp_product_master.csv"),
                    ("erp", "expected_delivery", "erp_purchase_orders.csv"),
                    ("pos", "sale", "pos_sales_export.csv"),
                    ("erp", "stock_on_hand", "erp_stock_on_hand.csv")],
    },
    "odoo": {
        "mappings": "mappings_odoo.json",
        "ids": [("odoo", "site", "odoo_ids_site.csv"),
                ("odoo", "supplier", "odoo_ids_supplier.csv"),
                ("odoo", "product", "odoo_ids_product.csv")],
        "uploads": [("odoo", "product", "odoo_products.csv"),
                    ("odoo", "expected_delivery", "odoo_purchase_orders.csv"),
                    ("odoo", "sale", "odoo_pos_orders.csv"),
                    ("odoo", "stock_on_hand", "odoo_stock_on_hand.csv")],
    },
}


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--base", default="http://localhost:8000/api/v1")
    ap.add_argument("--email", default="head_office@neuro.local")
    ap.add_argument("--password", default="123456")
    ap.add_argument("--style", choices=sorted(STYLES), default="odoo")
    args = ap.parse_args()
    style = STYLES[args.style]
    csv_headers = {"content-type": "text/csv"}
    with httpx.Client(base_url=args.base, timeout=60) as c:
        token = c.post("/auth/login", json={"email": args.email, "password": args.password}).raise_for_status().json()
        headers = {"Authorization": f"Bearer {token['access_token']}"}
        for source, entity, name in style["ids"]:
            r = c.post(f"/connect/id-mappings/{source}/{entity}/csv", headers={
                **headers, **csv_headers}, content=(SAMPLES / name).read_bytes())
            print(f"id mappings {source}/{entity}: {r.status_code} {r.json()}")
        mappings = json.loads((SAMPLES / style["mappings"]).read_text(encoding="utf-8"))
        for key, spec in mappings.items():
            source, entity = key.split("/")
            body = spec if "columns" in spec else {"columns": spec}
            r = c.put(f"/connect/csv-mappings/{source}/{entity}", json=body, headers=headers)
            print(f"mapping {key}: {r.status_code}")
        for source, entity, name in style["uploads"]:
            r = c.post(f"/connect/csv/{entity}", params={"source_system": source},
                       content=(SAMPLES / name).read_bytes(), headers={**headers, **csv_headers})
            print(f"{name}: {r.status_code} {json.dumps(r.json(), indent=2)}")


if __name__ == "__main__":
    main()
