#!/usr/bin/env python3
"""
Fetch job orders from FPSMS backend by plan date.
Uses the public API GET /py/job-orders (no login required).

Usage:
  python fetch_job_orders.py                    # today
  python fetch_job_orders.py 2026-02-24         # specific date
  python fetch_job_orders.py --date 2026-02-24
"""

import argparse
import os
import sys
from datetime import date
from typing import List, Optional

import requests

DEFAULT_BASE_URL = os.environ.get("FPSMS_BASE_URL", "http://localhost:8090/api")


def fetch_job_orders(base_url: str, plan_start: Optional[date]) -> List[dict]:
    """Call GET /py/job-orders and return the JSON list."""
    url = f"{base_url.rstrip('/')}/py/job-orders"
    params = {}
    if plan_start is not None:
        params["planStart"] = plan_start.isoformat()
    resp = requests.get(url, params=params, timeout=30)
    resp.raise_for_status()
    return resp.json()


def main() -> None:
    parser = argparse.ArgumentParser(description="Fetch job orders from FPSMS by plan date")
    parser.add_argument(
        "date",
        nargs="?",
        type=str,
        default=None,
        help="Plan date (yyyy-MM-dd). Default: today",
    )
    parser.add_argument(
        "--date",
        dest="date_alt",
        type=str,
        default=None,
        help="Plan date (yyyy-MM-dd)",
    )
    parser.add_argument(
        "--base-url",
        type=str,
        default=DEFAULT_BASE_URL,
        help=f"Backend base URL (default: {DEFAULT_BASE_URL})",
    )
    args = parser.parse_args()

    plan_str = args.date_alt or args.date
    if plan_str:
        try:
            plan_start = date.fromisoformat(plan_str)
        except ValueError:
            print(f"Invalid date: {plan_str}. Use yyyy-MM-dd.", file=sys.stderr)
            sys.exit(1)
    else:
        plan_start = date.today()

    try:
        data = fetch_job_orders(args.base_url, plan_start)
    except requests.RequestException as e:
        print(f"Request failed: {e}", file=sys.stderr)
        sys.exit(1)

    print(f"Job orders for planStart={plan_start} ({len(data)} items)")
    for jo in data:
        print(f"  id={jo.get('id')} code={jo.get('code')} itemCode={jo.get('itemCode')} itemName={jo.get('itemName')} reqQty={jo.get('reqQty')}")


if __name__ == "__main__":
    main()
