from woocommerce import API
from flask import current_app


def _client():
    cfg = current_app.config
    return API(
        url=cfg['WC_URL'],
        consumer_key=cfg['WC_KEY'],
        consumer_secret=cfg['WC_SECRET'],
        version='wc/v3',
        timeout=15,
    )


def mark_completed(order_id: str) -> dict:
    """Set a WooCommerce order status to 'completed'."""
    wcapi = _client()
    resp = wcapi.put(f"orders/{order_id}", {"status": "completed"})
    resp.raise_for_status()
    return resp.json()


def add_tracking_note(order_id: str, tracking: str, carrier: str) -> dict:
    """Add a private order note with tracking information."""
    wcapi = _client()
    note_text = f"Shipment dispatched via {carrier}. Tracking number: {tracking}"
    resp = wcapi.post(f"orders/{order_id}/notes", {
        "note": note_text,
        "customer_note": False,
    })
    resp.raise_for_status()
    return resp.json()
