#!/usr/bin/env python3
"""
Voting/Consensus Example

Demonstrates how to use multi-agent voting for decision making.

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

import asyncio
import logging

from agent_orchestrator import Orchestrator
from agent_orchestrator.voting import (
    VotingCoordinator,
    QuorumType,
    VotingSession,
)

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


async def main():
    """Run a multi-agent voting session."""

    orchestrator = Orchestrator()

    try:
        await orchestrator.start()

        # Create voting coordinator
        coordinator = VotingCoordinator()

        # Create a voting session
        session = await coordinator.create_session(
            topic="Which database should we use for the new microservice?",
            options=["PostgreSQL", "MongoDB", "SQLite", "Redis"],
            required_voters=["claude-code", "gemini-cli", "codex-cli"],
            quorum_type=QuorumType.SIMPLE_MAJORITY,
            deadline_seconds=300,
        )

        logger.info(f"Voting session created: {session.id}")
        logger.info(f"Topic: {session.topic}")
        logger.info(f"Options: {session.options}")

        # Simulate agents casting votes
        # In real usage, agents would analyze the context and vote

        await coordinator.cast_vote(
            session_id=session.id,
            agent_id="claude-code",
            choice="PostgreSQL",
            confidence=0.85,
            rationale="PostgreSQL offers strong ACID compliance and is well-suited "
            "for relational data with complex queries.",
        )

        await coordinator.cast_vote(
            session_id=session.id,
            agent_id="gemini-cli",
            choice="PostgreSQL",
            confidence=0.75,
            rationale="PostgreSQL has excellent documentation and community support. "
            "Good choice for structured data.",
        )

        await coordinator.cast_vote(
            session_id=session.id,
            agent_id="codex-cli",
            choice="MongoDB",
            confidence=0.60,
            rationale="MongoDB might be better for flexibility if requirements change.",
        )

        # Tally votes
        result = await coordinator.tally_votes(session.id)

        # Display results
        print("\n" + "=" * 60)
        print("VOTING RESULTS")
        print("=" * 60)

        print(f"\nTopic: {session.topic}")
        print(f"Quorum Type: {session.quorum_type.value}")
        print(f"Total Votes: {result.total_votes}")
        print(f"Quorum Met: {'Yes' if result.quorum_met else 'No'}")

        print("\nVotes by Option:")
        for option, count in result.vote_counts.items():
            percentage = (count / result.total_votes) * 100 if result.total_votes else 0
            bar = "█" * int(percentage / 5)
            print(f"  {option}: {count} ({percentage:.0f}%) {bar}")

        print(f"\nWinner: {result.winner}")
        print(f"Confidence: {result.average_confidence:.0%}")

        print("\nVote Details:")
        for vote in result.votes:
            print(f"  {vote.agent_id}: {vote.choice}")
            print(f"    Confidence: {vote.confidence:.0%}")
            print(f"    Rationale: {vote.rationale[:100]}...")

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

    finally:
        await orchestrator.shutdown()


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