import json
import os

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "http://drafter.cadel.me",
    "https://drafter.cadel.me",
    "http://localhost",
    "http://localhost:1234",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


def discover_sets():
    # find all set directories
    sets = []
    for root, dirs, files in os.walk("data/sets"):
        for dir in dirs:
            sets.append(dir)

    return sets


@app.get("/sets")
def read_sets():
    sets = discover_sets()
    return {"sets": sets}


@app.get("/sets/{set_name}/cards")
def read_item(set_name: str):
    if set_name not in discover_sets():
        return {"error": "Set not found"}

    card_data_path = os.path.join("data", "sets", set_name, "card-data.json")

    with open(card_data_path) as f:
        card_data = json.load(f)

    return {"data": card_data}


@app.get("/sets/{set_name}/ratings")
def read_item(set_name: str):
    if set_name not in discover_sets():
        return {"error": "Set not found"}

    card_ratings_path = os.path.join("data", "sets", set_name, "card-ratings-all.json")

    with open(card_ratings_path) as f:
        card_data = json.load(f)

    return {"data": card_data}
