"""Multi-firm overview — KPIs for all companies the user can access, side-by-side."""
from datetime import datetime, timezone
from fastapi import APIRouter, Depends, Request
from auth import get_current_user

router = APIRouter(prefix="/api/firms", tags=["firms"])


@router.get("/overview")
async def firms_overview(request: Request, user=Depends(get_current_user)):
    """For each company, compute: this-month sales/purchases/profit, AR/AP, stock value, party/item counts."""
    db = request.app.state.db
    companies = await db.companies.find({}).to_list(500)
    today = datetime.now(timezone.utc)
    month_start = today.replace(day=1, hour=0, minute=0, second=0, microsecond=0).isoformat()

    rows = []
    for c in companies:
        cid = str(c["_id"])
        q = {"company_id": cid}
        m_q = {**q, "created_at": {"$gte": month_start}}

        sales_m = await db.invoices.find({**m_q, "type": "sale"}, {"subtotal": 1, "total": 1, "amount_received": 1, "payment_received": 1}).to_list(10000)
        pur_m = await db.invoices.find({**m_q, "type": "purchase"}, {"subtotal": 1, "total": 1}).to_list(10000)
        all_sales = await db.invoices.find({**q, "type": "sale"}, {"total": 1, "amount_received": 1, "payment_received": 1}).to_list(50000)
        all_pur = await db.invoices.find({**q, "type": "purchase"}, {"total": 1, "amount_received": 1, "payment_received": 1}).to_list(50000)
        items = await db.items.find(q, {"current_stock": 1, "purchase_price": 1, "low_stock_threshold": 1}).to_list(50000)
        party_ct = await db.parties.count_documents(q)

        rev = sum(float(s.get("subtotal", 0)) for s in sales_m)
        cogs = sum(float(p.get("subtotal", 0)) for p in pur_m)
        ar = sum(max(0.0, float(s.get("total", 0)) - float(s.get("amount_received", s.get("payment_received", 0)))) for s in all_sales)
        ap = sum(max(0.0, float(p.get("total", 0)) - float(p.get("amount_received", p.get("payment_received", 0)))) for p in all_pur)
        stock_value = sum(float(it.get("current_stock", 0)) * float(it.get("purchase_price", 0)) for it in items)
        low_stock = sum(1 for it in items if (it.get("current_stock") or 0) <= (it.get("low_stock_threshold") or 0) and (it.get("low_stock_threshold") or 0) > 0)

        rows.append({
            "id": cid,
            "name": c.get("name"),
            "gstin": c.get("gstin", ""),
            "state": c.get("state", ""),
            "industry": c.get("industry", ""),
            "this_month_sales": round(rev, 2),
            "this_month_purchases": round(cogs, 2),
            "this_month_profit": round(rev - cogs, 2),
            "receivable": round(ar, 2),
            "payable": round(ap, 2),
            "stock_value": round(stock_value, 2),
            "low_stock_count": low_stock,
            "party_count": party_ct,
            "item_count": len(items),
            "sale_count_month": len(sales_m),
        })

    rows.sort(key=lambda r: -r["this_month_sales"])
    return rows
