"""Nov 12: create, read, update, and delete courses, with request and response models.

This is the code from today's slides, as one program you can run and change.
It writes to your planner.db, so to undo everything you did with it, run
"python scripts/load.py --drop" in your planner clone.

Setup is the same as practice_api.py:

  1. Set PLANNER_DB below to the planner.db file in your clone.
  2. Activate your planner virtual environment, then run:

         fastapi dev backend_demo.py

  3. Open http://127.0.0.1:8000/docs in a browser.
"""

import os
from decimal import Decimal
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}"

from fastapi import FastAPI, HTTPException
from planner.core import Course, SessionDep
from sqlalchemy.exc import IntegrityError
from sqlmodel import Field, SQLModel

app = FastAPI(title="Backend Demo")


# --------------------------------------------------------------------------
# Three classes describe what crosses the network. None of them is a table.
# --------------------------------------------------------------------------


class CourseCreate(SQLModel):
    """What a client sends to create a course: no course_id, which the database picks."""

    subject_code: str = Field(max_length=4)
    number: str = Field(max_length=5)
    title: str = Field(min_length=1)
    credits: Decimal = Field(default=Decimal("3.0"), ge=0, max_digits=3, decimal_places=1)


class CoursePublic(SQLModel):
    """What a client receives: every column here is safe to show anyone."""

    course_id: int
    subject_code: str
    number: str
    title: str
    credits: Decimal


class CourseUpdate(SQLModel):
    """What a client may change, and nothing else: every field is optional."""

    title: str | None = Field(default=None, min_length=1)
    credits: Decimal | None = Field(default=None, ge=0, max_digits=3, decimal_places=1)
    is_active: bool | None = None


def get_course(session: SessionDep, course_id: int) -> Course:
    """Return the course, or stop the request with a 404."""
    course = session.get(Course, course_id)
    if course is None:
        raise HTTPException(status_code=404, detail="Course not found")
    return course


def commit_or_409(session: SessionDep, detail: str) -> None:
    """Commit, or roll back and stop the request with a 409 if a constraint fails."""
    try:
        session.commit()
    except IntegrityError:
        # After a failed commit the session refuses to do anything else
        # until it is rolled back.
        session.rollback()
        raise HTTPException(status_code=409, detail=detail) from None


# --------------------------------------------------------------------------
# Read: GET returns 200, or 404 when the path names a course that does not exist.
# --------------------------------------------------------------------------


@app.get("/courses/{course_id}")
def read_course(course_id: int, session: SessionDep) -> CoursePublic:
    return get_course(session, course_id)


# --------------------------------------------------------------------------
# Create: POST returns 201 and the new course, including the id it was given.
#
#   POST /courses with {"subject_code": "CS", "number": "375", "title": "Web Databases"}
#       -> 201
#   ... the same request again  -> 409, since (subject_code, number) is UNIQUE
#   ... with "subject_code": "XYZ"  -> 409, since there is no such subject
#   ... with no title  -> 422, before this function ever runs
# --------------------------------------------------------------------------


@app.post("/courses", status_code=201)
def create_course(data: CourseCreate, session: SessionDep) -> CoursePublic:
    course = Course.model_validate(data)
    session.add(course)
    commit_or_409(session, "That course already exists, or its subject does not")
    session.refresh(course)  # load the course_id the database chose
    return course


# --------------------------------------------------------------------------
# Update: PATCH changes only the fields the client sent.
#
#   PATCH /courses/625 with {"title": "Database Systems I"}  -> 200, credits unchanged
#   PATCH /courses/625 with {"credits": "four"}  -> 422
# --------------------------------------------------------------------------


@app.patch("/courses/{course_id}")
def update_course(course_id: int, data: CourseUpdate, session: SessionDep) -> CoursePublic:
    course = get_course(session, course_id)
    # exclude_unset: only the fields in the request body, not every field
    # with its default of None, which would erase the title and the credits.
    course.sqlmodel_update(data.model_dump(exclude_unset=True))
    commit_or_409(session, "The change breaks a constraint")
    session.refresh(course)
    return course


# --------------------------------------------------------------------------
# Delete: DELETE returns 204 and no body.
#
#   DELETE /courses/<the id of the course you just created>  -> 204
#   DELETE /courses/625  -> 409: other teams' tables refer to CS 374
#   DELETE /courses/99999  -> 404
# --------------------------------------------------------------------------


@app.delete("/courses/{course_id}", status_code=204)
def delete_course(course_id: int, session: SessionDep) -> None:
    session.delete(get_course(session, course_id))
    commit_or_409(session, "Other rows refer to this course")
