#!/usr/bin/env python3
"""
Cost Tracking Example

Demonstrates how to monitor costs and get optimization recommendations.

Usage:
    python examples/advanced/cost_tracking.py
"""

import asyncio
import logging
from datetime import datetime, timedelta

from agent_orchestrator import Orchestrator
from agent_orchestrator.budget import (
    BudgetEnforcer,
    CostOptimizer,
    UsageRecord,
    get_cost_optimizer,
)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


async def main():
    """Monitor costs and get optimization recommendations."""

    orchestrator = Orchestrator()

    try:
        await orchestrator.start()

        # Get cost optimizer
        optimizer = get_cost_optimizer()

        # Get current costs
        api_client = orchestrator.get_api_client()

        # Fetch cost summary
        print("\n" + "=" * 60)
        print("COST SUMMARY")
        print("=" * 60)

        costs = await api_client.get("/costs?period=today")
        print(f"\nPeriod: Today")
        print(f"Total Spent: ${costs['total_cost_usd']:.2f}")
        print(f"Daily Budget: ${costs['budget_usd']:.2f}")
        print(f"Budget Used: {costs['percentage_used']:.0f}%")

        # Progress bar
        used = int(costs["percentage_used"] / 5)
        remaining = 20 - used
        bar = "█" * used + "░" * remaining
        print(f"[{bar}] {costs['percentage_used']:.0f}%")

        # Costs by agent
        print("\nCosts by Agent:")
        for agent_id, cost in costs.get("by_agent", {}).items():
            print(f"  {agent_id}: ${cost:.2f}")

        # Costs by model
        print("\nCosts by Model:")
        for model, cost in costs.get("by_model", {}).items():
            print(f"  {model}: ${cost:.2f}")

        # Get projections
        print("\n" + "=" * 60)
        print("COST PROJECTIONS")
        print("=" * 60)

        projections = await api_client.get("/costs/projections")
        print(f"\nProjected Daily: ${projections['projected_daily_usd']:.2f}")
        print(f"Projected Weekly: ${projections['projected_weekly_usd']:.2f}")
        print(f"Projected Monthly: ${projections['projected_monthly_usd']:.2f}")
        print(f"Trend: {projections['trend']}")
        print(f"Confidence: {projections['confidence']:.0%}")

        # Get recommendations
        print("\n" + "=" * 60)
        print("OPTIMIZATION RECOMMENDATIONS")
        print("=" * 60)

        recommendations = await api_client.get("/costs/recommendations?limit=5")

        if recommendations:
            for i, rec in enumerate(recommendations, 1):
                severity_icon = {"low": "💡", "medium": "⚠️", "high": "🚨"}.get(
                    rec["severity"], "📌"
                )
                print(f"\n{i}. {severity_icon} {rec['type']}")
                print(f"   {rec['recommendation']}")
                print(f"   Potential Savings: ${rec['potential_savings_usd']:.2f}")
        else:
            print("\nNo optimization recommendations at this time.")

        # Budget alerts
        print("\n" + "=" * 60)
        print("BUDGET ALERTS")
        print("=" * 60)

        alerts = await api_client.get("/rate-limits/alerts")

        if alerts:
            for alert in alerts:
                alert_icon = {
                    "warning": "⚠️",
                    "critical": "🚨",
                    "exhausted": "🔴",
                }.get(alert["alert_type"], "📌")
                print(f"\n{alert_icon} {alert['agent_id']}: {alert['message']}")
                print(f"   Triggered: {alert['triggered_at']}")
        else:
            print("\nNo active budget alerts.")

        print("\n" + "=" * 60 + "\n")

    finally:
        await orchestrator.shutdown()


if __name__ == "__main__":
    asyncio.run(main())
