"""Factor Market Example.

Demonstrates purchasing and using trading factors.
"""

from openclaw.factor import FactorStore
from openclaw.core.economy import TradingEconomicTracker
from openclaw.factor.types import FactorContext
from datetime import datetime


def main():
    """Run the factor market example."""
    print("=" * 60)
    print("OpenClaw Trading - Factor Market Example")
    print("=" * 60)

    # 1. Initialize
    print("\n1. Initializing factor store...")
    tracker = TradingEconomicTracker(agent_id="factor_trader")
    store = FactorStore(agent_id="factor_trader", tracker=tracker)
    print(f"   Agent ID: factor_trader")
    print(f"   Initial Balance: ${tracker.balance:,.2f}")

    # 2. List available factors
    print("\n2. Available Factors:")
    factors = store.list_available()

    basic_factors = [f for f in factors if f['price'] == 0]
    advanced_factors = [f for f in factors if f['price'] > 0]

    print("\n   Basic (Free):")
    for f in basic_factors[:3]:
        print(f"     - {f['name']} ({f['id']})")

    print("\n   Advanced (Paid):")
    for f in advanced_factors[:3]:
        print(f"     - {f['name']} ({f['id']}): ${f['price']}")

    # 3. Use a basic factor
    print("\n3. Using basic factor (MA Crossover)...")
    factor = store.get_factor("buy_ma_crossover")
    if factor:
        print(f"   Factor: {factor.metadata.name}")
        print(f"   Type: {factor.metadata.factor_type.value}")
        print(f"   Unlocked: {factor.is_unlocked}")

        # Create evaluation context
        context = FactorContext(
            symbol="AAPL",
            equity=10000.0,
        )

        result = factor.evaluate(context)
        print(f"   Signal: {result.signal.value if hasattr(result, 'signal') else result}")

    # 4. Try to purchase advanced factor
    print("\n4. Purchasing advanced factor (ML Prediction)...")
    result = store.purchase("buy_ml_prediction")
    print(f"   Success: {result.success}")
    print(f"   Message: {result.message}")
    print(f"   Remaining Balance: ${tracker.balance:,.2f}")

    # 5. Check inventory
    print("\n5. Factor Inventory:")
    print(f"   Total Factors: {len(store.inventory)}")
    print(f"   Unlocked: {sum(1 for f in store.inventory.values() if f.unlocked)}")

    # 6. Get purchase history
    print("\n6. Purchase History:")
    history = store.get_purchase_history()
    print(f"   Total Purchases: {len(history)}")
    total_spent = sum(p.price for p in history)
    print(f"   Total Spent: ${total_spent:,.2f}")

    print("\n" + "=" * 60)
    print("Factor market example complete!")
    print("=" * 60)


if __name__ == "__main__":
    main()
