import httpx
import json
import pathlib
from . import app
from flask import request

BASE_API_URL = "https://scrapple.fly.io/hearings/house/118/"
BASE_DIR = pathlib.Path("data/congress-hearing-118-house")


def _load_hearings():
    all = {}
    for hfile in BASE_DIR.glob("*.json"):
        data = json.loads(hfile.read_text())
        all[data["request"]["jacketNumber"]] = data
    return all


ALL_HEARINGS = _load_hearings()
HEARING_IDS = list(ALL_HEARINGS.keys())  # semi-consistent ordering


def shortened(hearing):
    """return compact hearing form for list view"""
    return {
        "chamber": hearing["request"]["chamber"],
        "congress": hearing["request"]["congress"],
        "jacketNumber": hearing["request"]["jacketNumber"],
        "updateDate": hearing["hearing"]["updateDate"],
        "url": BASE_API_URL + hearing["request"]["jacketNumber"],
    }


@app.route("/hearings")
def hearings_list():
    offset = int(request.args.get("offset", 0))
    limit = int(request.args.get("limit", 50))
    format = request.args.get("format", "json")
    if offset + limit > len(ALL_HEARINGS):
        next_url = None
    else:
        next_url = str(
            httpx.URL(BASE_API_URL).copy_with(
                params={"offset": offset + limit, "limit": limit, "format": format}
            )
        )
    hearing_ids = HEARING_IDS[offset : offset + limit]
    hearings = [ALL_HEARINGS[h] for h in hearing_ids]
    return {
        "hearings": [shortened(h) for h in hearings],
        "pagination": {"count": len(ALL_HEARINGS), "next": next_url},
        "chamber": {
            "chamber": "house",
            "congress": "118",
            "contentType": "application/json",
            "format": "json",
        },
    }


@app.route("/hearings/<jacket_id>")
def hearings_detail(jacket_id):
    return ALL_HEARINGS[jacket_id]
