"""Example: TweedeKamerAPI usage - from api_client.py and actual codebase."""

from datetime import datetime, timedelta
from typing import Dict, List

# Import the API client
from api_client import TweedeKamerAPI


# =============================================================================
# Example 1: Basic API usage
# =============================================================================


def example_fetch_motions():
    """Fetch recent parliamentary motions from TweedeKamer API."""

    api = TweedeKamerAPI()

    # Fetch motions from last 30 days
    start_date = datetime.now() - timedelta(days=30)

    try:
        motions = api.get_motions(start_date=start_date, limit=100)

        print(f"Fetched {len(motions)} motions")

        for motion in motions[:5]:  # Show first 5
            print(f"  - {motion.get('title', 'N/A')}")

        return motions
    finally:
        api.close()


# =============================================================================
# Example 2: Fetching with date range
# =============================================================================


def example_date_range():
    """Fetch motions from a specific date range."""

    api = TweedeKamerAPI()

    start = datetime(2024, 1, 1)
    end = datetime(2024, 3, 31)  # Q1 2024

    try:
        motions = api.get_motions(start_date=start, end_date=end, limit=500)

        # Group by policy area
        by_area = {}
        for m in motions:
            area = m.get("policy_area", "Onbekend")
            by_area.setdefault(area, []).append(m)

        for area, area_motions in sorted(by_area.items()):
            print(f"{area}: {len(area_motions)} motions")

        return motions
    finally:
        api.close()


# =============================================================================
# Example 3: Context manager usage
# =============================================================================


def example_context_manager():
    """Use API client as context manager."""

    with TweedeKamerAPI() as api:
        motions = api.get_motions(
            start_date=datetime.now() - timedelta(days=7), limit=50
        )

        print(f"Fetched {len(motions)} motions this week")

        return motions


# =============================================================================
# Example 4: Processing voting records
# =============================================================================


def example_process_votes():
    """Process individual voting records from API."""

    api = TweedeKamerAPI()

    start_date = datetime.now() - timedelta(days=7)

    try:
        # Get voting records directly
        voting_records, besluit_meta = api._get_voting_records(
            start_date=start_date, limit=1000
        )

        print(f"Fetched {len(voting_records)} voting records")
        print(f"From {len(besluit_meta)} unique decisions")

        # Count votes by party
        party_votes = {}
        for record in voting_records:
            party = record.get("Fractie", "Onbekend")
            vote = record.get("Soort", "Onbekend")
            party_votes.setdefault(party, {})[vote] = (
                party_votes.get(party, {}).get(vote, 0) + 1
            )

        for party, votes in sorted(party_votes.items()):
            total = sum(votes.values())
            voor = votes.get("Voor", 0)
            print(f"{party}: {total} votes ({voor} voor)")

        return voting_records
    finally:
        api.close()


# =============================================================================
# Example 5: Safe API call with fallback
# =============================================================================


def example_safe_call():
    """Make API call with safe fallback on failure."""

    api = TweedeKamerAPI()

    try:
        # This will return [] on any error
        motions = api.get_motions(
            start_date=datetime.now() - timedelta(days=30), limit=100
        )

        if not motions:
            print("No motions returned - using cached data")
            # Fallback to cached/local data
            from database import db

            return db.get_filtered_motions(limit=10)

        return motions
    finally:
        api.close()


# =============================================================================
# Example 6: Pagination handling
# =============================================================================


def example_pagination():
    """Understand how pagination works in the API."""

    api = TweedeKamerAPI()

    start_date = datetime.now() - timedelta(days=365)

    # Simulate pagination
    page_size = 250
    total_limit = 500

    all_motions = []
    skip = 0

    while len(all_motions) < total_limit:
        print(f"Fetching page with skip={skip}...")

        # In real usage, get_motions handles pagination internally
        # This demonstrates what's happening under the hood
        page_motions = api._fetch_page(start_date=start_date, skip=skip, top=page_size)

        if not page_motions:
            break

        all_motions.extend(page_motions)
        skip += page_size

        if len(page_motions) < page_size:
            break  # Last page

    print(f"Total fetched: {len(all_motions)} motions")
    return all_motions


if __name__ == "__main__":
    print("=== Basic Fetch ===")
    example_fetch_motions()

    print("\n=== Process Votes ===")
    example_process_votes()
