"""Example: MotionDatabase usage - from database.py and actual codebase."""

from typing import Dict, List, Optional
import duckdb
import json
from config import config

# Import the singleton instance
from database import db


# =============================================================================
# Example 1: Getting filtered motions
# =============================================================================


def example_get_filtered_motions():
    """Get controversial motions from a specific policy area."""

    motions = db.get_filtered_motions(
        policy_area="Klimaat",
        min_margin=0.0,
        max_margin=0.3,  # Controversial: close margin
        limit=10,
    )

    for motion in motions:
        print(f"{motion['title']}: {motion['winning_margin']:.1%} margin")

    return motions


# =============================================================================
# Example 2: Creating a voting session
# =============================================================================


def example_voting_session():
    """Create a new user session and record votes."""

    # Create session for 10 motions
    session_id = db.create_session(total_motions=10)
    print(f"Created session: {session_id}")

    # Get motions for the session
    motions = db.get_filtered_motions(policy_area="Alle", limit=10)

    # Record votes
    for motion in motions:
        # In real app, user would choose vote
        vote = "Voor"  # Example vote
        db.record_vote(session_id=session_id, motion_id=motion["id"], vote=vote)

    # Get results
    results = db.get_party_results(session_id)

    for party, result in sorted(results.items(), key=lambda x: -x[1]["agreement"]):
        print(f"{party}: {result['agreement']:.1%} agreement")

    return results


# =============================================================================
# Example 3: Working with DuckDB connections directly
# =============================================================================


def example_direct_duckdb():
    """Example of proper DuckDB connection handling."""

    conn = duckdb.connect(config.DATABASE_PATH)
    try:
        # Get motion with votes
        result = conn.execute(
            """
            SELECT m.*, 
                   JSON_EXTRACT(voting_results, '$.total_votes') as total_votes
            FROM motions m
            WHERE m.id = ?
        """,
            (123,),
        ).fetchone()

        if result:
            print(f"Motion: {result[1]}")  # title is index 1

        return result
    finally:
        conn.close()


# =============================================================================
# Example 4: Bulk operations
# =============================================================================


def example_bulk_insert():
    """Example of bulk inserting motions."""

    # Sample data
    motions = [
        {
            "title": "Motion about climate policy",
            "description": "Proposal to reduce emissions",
            "date": "2024-01-15",
            "policy_area": "Klimaat",
            "voting_results": json.dumps({"Voor": 75, "Tegen": 65}),
            "winning_margin": 0.07,
            "controversy_score": 0.85,
        },
        {
            "title": "Motion about healthcare",
            "description": "Increase healthcare budget",
            "date": "2024-01-20",
            "policy_area": "Zorg",
            "voting_results": json.dumps({"Voor": 90, "Tegen": 50}),
            "winning_margin": 0.29,
            "controversy_score": 0.42,
        },
    ]

    conn = duckdb.connect(config.DATABASE_PATH)
    try:
        for motion in motions:
            conn.execute(
                """
                INSERT INTO motions 
                (title, description, date, policy_area, voting_results, 
                 winning_margin, controversy_score)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            """,
                (
                    motion["title"],
                    motion["description"],
                    motion["date"],
                    motion["policy_area"],
                    motion["voting_results"],
                    motion["winning_margin"],
                    motion["controversy_score"],
                ),
            )
        conn.close()
        print(f"Inserted {len(motions)} motions")
    except Exception as e:
        conn.close()
        print(f"Error inserting motions: {e}")


# =============================================================================
# Example 5: Query with aggregation
# =============================================================================


def example_aggregation():
    """Example of aggregate queries."""

    conn = duckdb.connect(config.DATABASE_PATH)
    try:
        # Get statistics by policy area
        results = conn.execute("""
            SELECT 
                policy_area,
                COUNT(*) as motion_count,
                AVG(winning_margin) as avg_margin,
                AVG(controversy_score) as avg_controversy
            FROM motions
            WHERE policy_area IS NOT NULL
            GROUP BY policy_area
            ORDER BY motion_count DESC
        """).fetchall()

        for row in results:
            print(
                f"{row[0]}: {row[1]} motions, "
                f"avg margin {row[2]:.1%}, "
                f"controversy {row[3]:.2f}"
            )

        conn.close()
        return results
    except Exception as e:
        conn.close()
        return []


if __name__ == "__main__":
    print("=== Filtered Motions ===")
    example_get_filtered_motions()

    print("\n=== Aggregation ===")
    example_aggregation()
