#!/usr/bin/env python3
"""
Probe Simpro API WIP data for all branches.
Run from backend/: python3 test_simpro_api.py
"""
import os
import json
import requests
from pathlib import Path
from dotenv import load_dotenv

load_dotenv(Path(__file__).resolve().parent.parent / ".env")

BRANCHES = {
    "Busselton": {
        "api_key": os.getenv("SIMPRO_BRANCH1_API_KEY", ""),
        "api_url": os.getenv("SIMPRO_BRANCH1_API_URL", ""),
        "companies": {139: "Electrical", 172: "Air"},
    },
    "Bunbury": {
        "api_key": os.getenv("SIMPRO_BRANCH2_API_KEY", ""),
        "api_url": os.getenv("SIMPRO_BRANCH2_API_URL", ""),
        "companies": {2: "Residential", 3: "Air", 4: "Solar", 5: "Commercial"},
    },
    "Mandurah": {
        "api_key": os.getenv("SIMPRO_BRANCH3_API_KEY", ""),
        "api_url": os.getenv("SIMPRO_BRANCH3_API_URL", ""),
        "companies": {2: "Electrical", 35: "Air"},
    },
}


def main():
    for branch_name, cfg in BRANCHES.items():
        api_key = cfg["api_key"]
        api_url = cfg["api_url"]
        if not api_key:
            print(f"  {branch_name}: SKIPPED (no API key)")
            continue

        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
            "Accept": "application/json",
        }

        print(f"\n{'='*50}")
        print(f"{branch_name}")
        print(f"{'='*50}")
        grand_count = 0
        grand_amount_to_invoice = 0.0
        for company_id, company_name in cfg["companies"].items():
            for stage in ["Pending", "Progress", "Complete"]:
                page = 1
                while True:
                    resp = requests.get(
                        f"{api_url}/companies/{company_id}/jobs/",
                        headers=headers,
                        params={
                            "pageSize": 250, "page": page, "Stage": stage,
                            "columns": "ID,Total,Totals,Stage",
                        },
                        timeout=15,
                    )
                    if resp.status_code != 200:
                        print(f"  {company_name} {stage}: HTTP {resp.status_code}")
                        break
                    items = resp.json()
                    if not items:
                        break
                    count = len(items)
                    page_amt = 0.0
                    for j in items:
                        total_obj = j.get("Total", {})
                        total_ex = total_obj.get("ExTax", 0) if isinstance(total_obj, dict) else 0
                        totals_obj = j.get("Totals", {})
                        inv_pct = totals_obj.get("InvoicePercentage", 0) if isinstance(totals_obj, dict) else 0
                        amt = total_ex * (100 - inv_pct) / 100 if inv_pct else total_ex
                        page_amt += amt
                    grand_count += count
                    grand_amount_to_invoice += page_amt
                    print(f"  {company_name:12s} {stage:10s} p{page}: {count:3d} jobs, AmtToInvoice=${page_amt:>12,.2f}")
                    if count < 250:
                        break
                    page += 1

        print(f"\n  TOTAL: {grand_count} WIP jobs, Amount to Invoice = ${grand_amount_to_invoice:,.2f}")


if __name__ == "__main__":
    main()
