# app/utils/api.py
# -----------------------------------------------------------------------------
# Light API client with CSV fallbacks so your app runs before the backend is ready.
# Set API_BASE (e.g., export API_BASE=http://localhost:8000) to activate HTTP calls.
# Expected endpoints (US1, US3, US4):
#   GET  /inventory        -> inventory rows
#   GET  /orders           -> orders
#   GET  /order_status     -> order statuses
#   GET  /skus             -> master SKUs
#   GET  /forecast         -> per-SKU per-warehouse daily forecast rows
#   POST /transactions     -> record a transaction (sku, qty, type, warehouse)
# -----------------------------------------------------------------------------

import os
import requests
import pandas as pd
from pathlib import Path
from typing import Optional

API_BASE = os.getenv("API_BASE", "http://backend:8000")
DATA_DIR = Path(__file__).resolve().parents[1] / "data"   # app/data

from pandas import json_normalize

def _safe_get_json(path: str, fallback_csv: Optional[str] = None) -> Optional[pd.DataFrame]:
    if API_BASE:
        try:
            r = requests.get(f"{API_BASE}/{path}", timeout=5)
            r.raise_for_status()
            data = r.json()

            # Normalize nested JSON
            if isinstance(data, list):
                return json_normalize(data)
            elif isinstance(data, dict):
                return json_normalize([data])
            else:
                return pd.DataFrame(data)

        except Exception:
            pass  # try CSV fallback

    if fallback_csv:
        csv_path = DATA_DIR / fallback_csv
        if csv_path.exists():
            return pd.read_csv(csv_path)

    return None


# --- Resource helpers ---

def get_inventory() -> Optional[pd.DataFrame]:
    return _safe_get_json("inventory", "inventory.csv")

def get_orders() -> Optional[pd.DataFrame]:
    return _safe_get_json("orders", "orders.csv")

def get_order_status() -> Optional[pd.DataFrame]:
    return _safe_get_json("order_status", "order_status.csv")

def get_skus() -> Optional[pd.DataFrame]:
    return _safe_get_json("skus", "skus.csv")

def get_forecasts() -> Optional[pd.DataFrame]:
    """
    Forecasts should include at least:
      ['SKU', 'warehouse_id', 'date', 'forecast', 'projected_stockout_date']
    Fallback to app/data/forecasts.csv if you provide one before the API is ready.
    """
    return _safe_get_json("forecast", "forecasts.csv")

def post_transaction(payload: dict) -> dict:
    """
    Submit a transaction to /transactions. If API is not ready, return a mock accepted response.
    """
    if API_BASE:
        try:
            r = requests.post(f"{API_BASE}/transactions", json=payload, timeout=5)
            r.raise_for_status()
            return r.json()
        except Exception:
            # fall through to mock
            pass
    return {"status": "mock", "accepted": True, "payload": payload}
