"""One-shot script: verify every major API module responds from cnperpdimensions."""
import sys
import requests

BASE = "http://localhost:8010/api/v1"

COL_NAME   = 30
COL_STATUS = 8
COL_DETAIL = 60

def main():
    # --- Login ---
    try:
        resp = requests.post(
            f"{BASE}/auth/login-json",
            json={"username": "superadmin", "password": "Super@dmin123"},
            timeout=5,
        )
        resp.raise_for_status()
    except Exception as e:
        print(f"Login failed: {e}")
        sys.exit(1)

    tok = resp.json().get("access_token", "")
    if not tok:
        print("Login succeeded but no access_token returned.")
        sys.exit(1)
    H = {"Authorization": f"Bearer {tok}"}

    # --- Confirm DB ---
    db_name = "(unknown)"
    db_url   = "(unknown)"
    try:
        from app.core.database import engine
        from sqlalchemy import text
        with engine.connect() as conn:
            db_name = conn.execute(text("SELECT current_database()")).scalar()
        db_url = str(engine.url)
    except Exception as e:
        print(f"Warning: could not query DB directly — {e}")

    print(f"Engine DB:  {db_name}")
    print(f"Engine URL: {db_url}")
    print()

    # --- Endpoint checks ---
    checks = [
        ("Sales / Customers",       f"{BASE}/sales/customers/count"),
        ("Sales / Invoices",        f"{BASE}/sales/invoices?limit=1"),
        ("Sales / Sales",           f"{BASE}/sales/?limit=1"),
        ("Inventory / Products",    f"{BASE}/inventory/products?limit=1"),
        ("Purchases / Suppliers",   f"{BASE}/purchases/suppliers?limit=1"),
        ("Purchases / POs",         f"{BASE}/purchases/orders?limit=1"),
        ("Accounting / Accounts",   f"{BASE}/accounting/codes?limit=1"),
        ("Banking / Accounts",      f"{BASE}/banking/accounts?limit=1"),
        ("Users",                   f"{BASE}/users?limit=1"),
        ("Branches",                f"{BASE}/branches"),
        ("VAT Transactions",        f"{BASE}/vat/transactions?limit=1"),
        ("Asset Management",        f"{BASE}/asset-management/assets?limit=1"),
        ("Budgeting",               f"{BASE}/budgeting/budgets?limit=1"),
        ("Manufacturing Products",  f"{BASE}/manufacturing/products?limit=1"),
        ("POS Sessions",            f"{BASE}/pos/sessions?limit=1"),
        ("General Ledger Entries",  f"{BASE}/general-ledger/general-ledger?limit=1"),
        ("Settings",                f"{BASE}/settings/"),
        ("Quotations",              f"{BASE}/quotations?limit=1"),
        ("Job Cards",               f"{BASE}/job-cards?limit=1"),
        ("Serial Numbers",          f"{BASE}/serial-numbers?limit=1"),
        ("Unit of Measure",         f"{BASE}/unit-of-measure?limit=1"),
        ("Credit Notes",            f"{BASE}/credit-notes?limit=1"),
        ("Invoices",                f"{BASE}/invoices?limit=1"),
        ("Roles",                   f"{BASE}/roles"),
        ("Notifications",           f"{BASE}/notifications?limit=1"),
    ]

    print(f"{'Module':<{COL_NAME}} {'Status':<{COL_STATUS}} Result")
    print("-" * (COL_NAME + COL_STATUS + COL_DETAIL + 2))

    all_ok = True
    for name, url in checks:
        try:
            r = requests.get(url, headers=H, timeout=5)
            if r.status_code == 200:
                d = r.json()
                if isinstance(d, list):
                    detail = f"{len(d)} item(s)"
                elif isinstance(d, dict):
                    detail = ", ".join(f"{k}={v}" for k, v in list(d.items())[:2])
                else:
                    detail = str(d)[:COL_DETAIL]
                mark = "OK"
            else:
                detail = r.text[:COL_DETAIL].strip()
                mark = "FAIL"
                all_ok = False
            print(f"{name:<{COL_NAME}} {mark:<{COL_STATUS}} {detail}")
        except Exception as e:
            print(f"{name:<{COL_NAME}} {'ERROR':<{COL_STATUS}} {e}")
            all_ok = False

    print()
    print(f"Database:       {db_name}")
    print(f"All modules OK: {all_ok}")
    if not all_ok:
        sys.exit(1)


if __name__ == "__main__":
    main()
