"""Nov 10: your first endpoints, on the project's core tables.

The first two endpoints are written for you. Read each one, then write the
three TODOs below them. Problem 4 is optional, for extra credit.

Setup:

  1. Save this file anywhere outside your planner clone.
  2. Set PLANNER_DB below to the planner.db file in your clone.
     If it is missing or empty, run "python scripts/load.py --drop" there.
  3. Activate your planner virtual environment, then run:

         fastapi dev practice_api.py

  4. Open http://127.0.0.1:8000/docs in a browser.

Every time you save this file, the server restarts by itself. Test each
endpoint with "Try it out" on the /docs page, or type its URL into the
browser's address bar, such as http://127.0.0.1:8000/courses/625
"""

import os
from pathlib import Path

PLANNER_DB = Path.home() / "planner" / "planner.db"  # TODO: your clone's planner.db

if not PLANNER_DB.is_file():
    raise SystemExit(f"Set PLANNER_DB in this file: {PLANNER_DB} does not exist")

# planner.core reads DATABASE_URL when it is imported, so set it first.
os.environ["DATABASE_URL"] = f"sqlite:///{PLANNER_DB}"

# Some of these are unused until you finish the TODOs.
from fastapi import FastAPI, HTTPException
from planner.core import Course, SessionDep, Subject, Term
from sqlmodel import SQLModel, func, select

app = FastAPI(title="Practice API")


# --------------------------------------------------------------------------
# Example 1. A collection: every subject, in order.
#
#   GET /subjects
#
# The decorator says which requests this function answers: the method (get)
# and the path. The return type says what the JSON will look like, so FastAPI
# turns each Subject object into {"code": ..., "name": ...}.
#
# The session parameter is a dependency. FastAPI opens a database session
# before calling the function and closes it afterward; you never create one.
# --------------------------------------------------------------------------


@app.get("/subjects")
def list_subjects(session: SessionDep) -> list[Subject]:
    return session.exec(select(Subject).order_by(Subject.code)).all()


# --------------------------------------------------------------------------
# Example 2. One item, named by a path parameter.
#
#   GET /courses/625      -> 200 and one course
#   GET /courses/99999    -> 404 Not Found
#   GET /courses/abc      -> 422, before this function ever runs
#
# {course_id} in the path becomes the course_id argument. Because the
# argument is declared int, FastAPI converts "625" to 625 for you, and
# rejects "abc" with a 422 that says exactly what was wrong.
# --------------------------------------------------------------------------


@app.get("/courses/{course_id}")
def read_course(course_id: int, session: SessionDep) -> Course:
    course = session.get(Course, course_id)
    if course is None:
        raise HTTPException(status_code=404, detail="Course not found")
    return course


# --------------------------------------------------------------------------
# Problem 1. One course, named by its subject and number.
#
#   GET /courses/CS/374   -> 200 and the course titled "Database Systems"
#   GET /courses/CS/999   -> 404 Not Found
#
# Write a function with two path parameters, subject and number, both str.
# Select the course whose subject_code and number match (use .first(), which
# returns None when nothing matches), and raise a 404 as Example 2 does.
#
# Why str for number? Some course numbers have letters, such as 499A.
# --------------------------------------------------------------------------

# TODO: Problem 1


# --------------------------------------------------------------------------
# Problem 2. Search, using query parameters.
#
#   GET /courses?subject=CS                 -> the first 20 CS courses
#   GET /courses?subject=CS&limit=50        -> all 43 CS courses
#   GET /courses?subject=MATH&min_credits=4 -> the 15 MATH courses worth 4 or more
#   GET /courses?subject=IT&limit=5         -> the first 5 IT courses
#   GET /courses                            -> the first 20 courses
#
# A function argument that is not in the path is a query parameter: the part
# of the URL after the ?. Give each one a default so that it is optional:
#
#   subject: str | None = None
#   min_credits: int = 0
#   limit: int = 20
#
# Start from select(Course), add a .where() only when subject is not None,
# and order by subject_code, then number. Return a list[Course].
# --------------------------------------------------------------------------

# TODO: Problem 2


# --------------------------------------------------------------------------
# Problem 3. The terms in one year, in calendar order.
#
#   GET /terms?year=2026  -> Spring 2026, Summer 2026, Fall 2026
#   GET /terms            -> 422, because year is required
#
# A query parameter with no default is required. Order by term_code, which
# sorts the seasons in calendar order (1 = Spring, 5 = Summer, 8 = Fall).
#
# Then look at the /docs page: how does it show that year is required here,
# while subject in Problem 2 is not?
# --------------------------------------------------------------------------

# TODO: Problem 3


# --------------------------------------------------------------------------
# Problem 4 (optional). A result that is not a table.
#
#   GET /subjects/CS/stats  -> {"code": "CS", "courses": 43, "credits": 126.0}
#   GET /subjects/XYZ/stats -> 404 Not Found
#
# The class below is a SQLModel without table=True: it describes the shape
# of the JSON and nothing in the database. Declare it as the return type,
# compute the count and the sum of credits with func.count() and func.sum(),
# and return SubjectStats(code=..., courses=..., credits=...).
#
# Check that the subject exists first, with session.get(Subject, code).
# We'll use classes like this on Thursday to control what an endpoint sends.
# --------------------------------------------------------------------------


class SubjectStats(SQLModel):
    code: str
    courses: int
    credits: float


# TODO: Problem 4
