from __future__ import annotations

from typing import Any, Dict, List, Optional


def _round_amount(value: Any) -> float:
    try:
        return round(float(value or 0.0), 6)
    except (TypeError, ValueError):
        return 0.0


def _int(value: Any) -> int:
    try:
        return int(value or 0)
    except (TypeError, ValueError):
        return 0


def _recommendation(
    action: str,
    *,
    command: Optional[str] = None,
    target_section: Optional[str] = None,
    reason: Optional[str] = None,
    priority: int = 0,
) -> Dict[str, Any]:
    payload: Dict[str, Any] = {"action": action, "priority": int(priority)}
    if command:
        payload["command"] = command
    if target_section:
        payload["target_section"] = target_section
    if reason:
        payload["reason"] = reason
    return payload


def _review_status(
    *,
    critical_exceptions: int,
    warning_exceptions: int,
    review_queue: int,
    budget_gap_oas: float,
) -> str:
    if critical_exceptions > 0:
        return "critical"
    if warning_exceptions > 0 or review_queue > 0 or budget_gap_oas > 0:
        return "attention"
    return "stable"


def _top_recommendation(
    *,
    exceptions: Dict[str, Any],
    shared_desk: Dict[str, Any],
    principal_review: Dict[str, Any],
    asset_reviews: List[Dict[str, Any]],
    delegate_reviews: List[Dict[str, Any]],
) -> Dict[str, Any]:
    exception_items = list(exceptions.get("items") or [])
    if exception_items:
        first = dict(exception_items[0].get("recommendation") or {})
        if first:
            return {
                **first,
                "source": "exceptions",
                "priority": int(first.get("priority") or 100),
            }

    desk_recommendation = dict(shared_desk.get("recommendation") or {})
    if desk_recommendation:
        return {
            **desk_recommendation,
            "source": "shared_desk",
            "priority": int(desk_recommendation.get("priority") or 80),
        }

    candidates = [
        dict(principal_review.get("recommendation") or {}),
        *(dict(item.get("recommendation") or {}) for item in asset_reviews),
        *(dict(item.get("recommendation") or {}) for item in delegate_reviews),
    ]
    candidates = [item for item in candidates if item]
    if not candidates:
        return {}
    candidates.sort(
        key=lambda item: (
            -int(item.get("priority") or 0),
            str(item.get("action") or ""),
        )
    )
    return candidates[0]


def _build_asset_reviews(
    *,
    asset_feed: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
    reviews: List[Dict[str, Any]] = []
    for item in asset_feed:
        state = str(item.get("state") or "").strip()
        asset_id = str(item.get("asset_id") or "").strip()
        label = (
            str(item.get("suggested_name") or "").strip()
            or str(item.get("file_path") or "").strip()
            or asset_id
            or "—"
        )
        asset_class = str(item.get("asset_class") or "").strip()
        price_model = str(item.get("price_model") or "").strip()
        if state == "deprecated" and asset_id:
            reviews.append(
                {
                    "asset_id": asset_id,
                    "label": label,
                    "state": state,
                    "asset_class": asset_class,
                    "price_model": price_model,
                    "recommendation": _recommendation(
                        "archive_asset",
                        command=(
                            f'oas asset-archive {asset_id} --reason "deprecated asset cleanup"'
                        ),
                        target_section="portfolio",
                        reason="deprecated assets should leave active circulation cleanly",
                        priority=70,
                    ),
                }
            )
        elif state == "live" and asset_class == "open_source_source" and price_model == "free":
            reviews.append(
                {
                    "asset_id": asset_id,
                    "label": label,
                    "state": state,
                    "asset_class": asset_class,
                    "price_model": price_model,
                    "recommendation": _recommendation(
                        "keep_free",
                        command="monitor distribution and keep this open-source asset free",
                        target_section="portfolio",
                        reason="open-source source assets work best as free distribution surfaces",
                        priority=20,
                    ),
                }
            )
    reviews.sort(
        key=lambda item: (
            -int(((item.get("recommendation") or {}).get("priority")) or 0),
            str(item.get("label") or ""),
        )
    )
    return reviews[:6]


def _build_delegate_reviews(
    *,
    delegate_rows: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
    reviews: List[Dict[str, Any]] = []
    for row in delegate_rows:
        delegate_id = str(row.get("delegate_id") or "").strip()
        if not delegate_id:
            continue
        failed_execution = _int(row.get("failed_execution"))
        failed = _int(row.get("failed"))
        pending_review = _int(row.get("pending_review"))
        execution_ready = _int(row.get("execution_ready"))
        budget_gap_oas = _round_amount(row.get("budget_gap_oas"))
        assets_created = _int(row.get("assets_created"))
        net_oas = _round_amount(row.get("net_oas"))
        recommendation: Dict[str, Any]
        if failed_execution > 0 or failed > 0:
            recommendation = _recommendation(
                "tighten_delegate_review",
                command="open Operations and inspect this delegate's failed actions",
                target_section="operations",
                reason="this delegate has recent failures and should stay under closer review",
                priority=80,
            )
        elif budget_gap_oas > 0:
            recommendation = _recommendation(
                "rebalance_delegate_budget",
                command="oas mandate status",
                target_section="policy",
                reason="this delegate is holding approved work beyond the current budget share",
                priority=60,
            )
        elif pending_review > 0 or execution_ready > 0:
            recommendation = _recommendation(
                "keep_delegate_active",
                command="oas agent status",
                target_section="operations",
                reason="this delegate is still carrying active queue pressure",
                priority=40,
            )
        elif assets_created > 0 or net_oas > 0:
            recommendation = _recommendation(
                "reward_delegate_scope",
                command="review Shared desk contribution and preserve its scope",
                target_section="operations",
                reason="this delegate is creating assets or positive net results",
                priority=25,
            )
        else:
            continue
        reviews.append(
            {
                "delegate_id": delegate_id,
                "executions": _int(row.get("executions")),
                "succeeded": _int(row.get("succeeded")),
                "failed": failed,
                "net_oas": net_oas,
                "assets_created": assets_created,
                "pending_review": pending_review,
                "execution_ready": execution_ready,
                "failed_execution": failed_execution,
                "allocated_budget_oas": _round_amount(row.get("allocated_budget_oas")),
                "budget_gap_oas": budget_gap_oas,
                "recommendation": recommendation,
            }
        )
    reviews.sort(
        key=lambda item: (
            -int(((item.get("recommendation") or {}).get("priority")) or 0),
            str(item.get("delegate_id") or ""),
        )
    )
    return reviews[:6]


def build_operating_review_summary(
    *,
    runtime_identity: Optional[Dict[str, Any]] = None,
    mandate: Optional[Dict[str, Any]] = None,
    portfolio_outcomes: Optional[Dict[str, Any]] = None,
    exceptions: Optional[Dict[str, Any]] = None,
    shared_desk: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    runtime_identity = dict(runtime_identity or {})
    mandate = dict(mandate or {})
    portfolio_outcomes = dict(portfolio_outcomes or {})
    exceptions = dict(exceptions or {})
    shared_desk = dict(shared_desk or {})

    principal = dict(runtime_identity.get("principal") or {})
    account = dict(runtime_identity.get("account") or {})
    principal_result = dict(portfolio_outcomes.get("principal_result") or {})
    asset_feed = list(portfolio_outcomes.get("asset_feed") or [])
    delegate_rows = list(shared_desk.get("delegates") or [])
    exception_counts = dict(exceptions.get("counts") or {})
    desk_budget = dict(shared_desk.get("budget") or {})
    desk_queues = dict(shared_desk.get("queues") or {})

    critical_exceptions = _int(exception_counts.get("critical"))
    warning_exceptions = _int(exception_counts.get("warning"))
    review_queue = _int((desk_queues.get("review") or {}).get("total"))
    budget_gap_oas = _round_amount(desk_budget.get("budget_gap_oas"))
    net_oas = _round_amount(principal_result.get("net_oas"))

    status = _review_status(
        critical_exceptions=critical_exceptions,
        warning_exceptions=warning_exceptions,
        review_queue=review_queue,
        budget_gap_oas=budget_gap_oas,
    )

    principal_recommendation = _recommendation(
        "monitor_results",
        command="oas agent status",
        target_section="operations",
        reason="the operating loop is healthy enough to keep monitoring",
        priority=10,
    )
    if critical_exceptions > 0:
        principal_recommendation = _recommendation(
            "stabilize_operations",
            command="oas agent status",
            target_section="operations",
            reason="critical execution blockers must be resolved before changing strategy",
            priority=95,
        )
    elif warning_exceptions > 0 or review_queue > 0:
        principal_recommendation = _recommendation(
            "clear_operator_backlog",
            command="open Candidates and clear pending review items",
            target_section="candidates",
            reason="review bottlenecks are preventing clean operating feedback",
            priority=70,
        )
    elif budget_gap_oas > 0:
        principal_recommendation = _recommendation(
            "rebalance_budget",
            command="oas mandate status",
            target_section="policy",
            reason="approved work is constrained by the current trade budget",
            priority=60,
        )
    elif net_oas < 0:
        principal_recommendation = _recommendation(
            "review_pricing_mix",
            command="open Portfolio and inspect live asset outcomes",
            target_section="portfolio",
            reason="the current portfolio is spending more than it returns",
            priority=40,
        )

    asset_reviews = _build_asset_reviews(asset_feed=asset_feed)
    delegate_reviews = _build_delegate_reviews(delegate_rows=delegate_rows)
    top_recommendation = _top_recommendation(
        exceptions=exceptions,
        shared_desk=shared_desk,
        principal_review={
            "recommendation": principal_recommendation,
        },
        asset_reviews=asset_reviews,
        delegate_reviews=delegate_reviews,
    )

    return {
        "cadence": {
            "daily": "review queue pressure, exceptions, and execution outcomes",
            "weekly": "adjust pricing, deprecations, archive decisions, and delegate scope",
        },
        "summary": {
            "status": status,
            "principal_id": str(principal.get("id") or account.get("id") or "").strip(),
            "net_oas": net_oas,
            "critical_exceptions": critical_exceptions,
            "warning_exceptions": warning_exceptions,
            "review_queue": review_queue,
            "execution_ready": _int((desk_queues.get("execution_ready") or {}).get("total")),
            "budget_gap_oas": budget_gap_oas,
            "active_recommendations": (
                len(asset_reviews) + len(delegate_reviews) + (1 if principal_recommendation else 0)
            ),
        },
        "top_recommendation": top_recommendation,
        "principal_review": {
            "principal_id": str(principal.get("id") or "").strip(),
            "carrier_type": str(principal.get("carrier_type") or "").strip(),
            "account_id": str(account.get("id") or "").strip(),
            "mandate_profile": str(mandate.get("profile") or "").strip(),
            "status": status,
            "net_oas": net_oas,
            "live_assets": _int(principal_result.get("live_assets")),
            "deprecated_assets": _int(principal_result.get("deprecated_assets")),
            "archived_assets": _int(principal_result.get("archived_assets")),
            "recommendation": principal_recommendation,
        },
        "asset_reviews": asset_reviews,
        "delegate_reviews": delegate_reviews,
    }
