#!/usr/bin/env python3
"""
OpenParliament EU — API quickstart
==================================

A minimal, dependency-light example of how to pull data from the
OpenParliament EU API for research or journalism.

Requirements:
    pip install requests pandas

Docs: http://localhost:8000/docs    (interactive)
Spec: http://localhost:8000/openapi.json
Data license: ODC-By 1.0 — please attribute OpenParliament EU.
"""

import requests
import pandas as pd

BASE = "http://localhost:8000/v1"   # change to the public host in production


def get(path, **params):
    r = requests.get(f"{BASE}{path}", params=params, timeout=60)
    r.raise_for_status()
    return r.json()


# ---------------------------------------------------------------
# 1. The 10 closest votes of the term
# ---------------------------------------------------------------
def closest_votes():
    data = get("/analytics/close-votes", limit=10)
    df = pd.DataFrame(data["results"])
    print("\n=== 10 closest main votes ===")
    print(df[["vote_date", "title", "votes_for", "votes_against", "margin"]].to_string(index=False))
    return df


# ---------------------------------------------------------------
# 2. The most rebellious Romanian MEPs
# ---------------------------------------------------------------
def rebel_meps(country="RO"):
    data = get("/analytics/rebel-votes", country=country, limit=10)
    df = pd.DataFrame(data["results"])
    print(f"\n=== Most rebellious {country} MEPs ===")
    print(df[["full_name", "group_code", "rebel_vote_count", "rebel_rate_pct"]].to_string(index=False))
    return df


# ---------------------------------------------------------------
# 3. Compare two MEPs head-to-head
# ---------------------------------------------------------------
def compare(id_a, id_b):
    data = get("/compare/meps", ids=f"{id_a},{id_b}")
    s = data["summary"]
    a, b = data["meps"]
    print(f"\n=== {a['full_name']} vs {b['full_name']} ===")
    if s["overall_similarity"] is not None:
        print(f"Overall similarity: {s['overall_similarity']*100:.1f}% "
              f"({s['same_votes']} of {s['comparable_votes']} comparable votes)")
    print("Top topic differences:")
    for t in sorted([t for t in data["topic_similarity"] if t["similarity"] is not None],
                    key=lambda t: t["similarity"])[:3]:
        print(f"  {t['topic_name']}: {t['similarity']*100:.1f}%")
    return data


# ---------------------------------------------------------------
# 4. Bulk download all current MEPs into a DataFrame (via CSV)
# ---------------------------------------------------------------
def all_meps_dataframe():
    # The CSV export is the recommended way to pull the full dataset.
    df = pd.read_csv("http://localhost:8000/v1/members.csv")
    print(f"\n=== Loaded {len(df)} current MEPs ===")
    print(df.head().to_string(index=False))
    return df


if __name__ == "__main__":
    closest_votes()
    rebel_meps("RO")
    all_meps_dataframe()
    # compare(197490, 197491)   # uncomment with two real MEP ids
