"""HW6: a web API for the Vet Clinic.

Author: TODO your name

Run the server from this folder, with your planner venv active:

    fastapi dev hw6.py

then test each endpoint at http://127.0.0.1:8000/docs.

The models are in vet.py, and the data is in vet.db; do not edit either.
Each problem below lists the requests the autograder sends and what it
expects back. It runs them against a fresh copy of vet.db, so anything you
add or delete by hand on the /docs page does not affect your grade.
To start over with the original data, download vet.db again.
"""

# Some of these are unused until you finish the TODOs.
from datetime import datetime

from fastapi import FastAPI, HTTPException
from sqlalchemy.exc import IntegrityError
from sqlmodel import Field, SQLModel, func, select
from vet import Animal, Appointment, Employee, PetOwner, Service, SessionDep

app = FastAPI(title="Vet Clinic")


# --------------------------------------------------------------------------
# Example. The clinic's menu, cheapest first.
#
#   GET /services  -> 11 services, starting with "Nail trim"
# --------------------------------------------------------------------------


@app.get("/services")
def list_services(session: SessionDep) -> list[Service]:
    return session.exec(select(Service).order_by(Service.fee)).all()


# ==========================================================================
# Part 1: reading (Nov 10)
# ==========================================================================

# --------------------------------------------------------------------------
# Problem 1. One animal.
#
#   GET /animals/1    -> 200 and {"pet_id": 1, "name": "Michele", "species": "dog", "owner_id": 1}
#   GET /animals/999  -> 404 with the detail "Animal not found"
# --------------------------------------------------------------------------

# TODO: Problem 1


# --------------------------------------------------------------------------
# Problem 2. Search the animals.
#
#   GET /animals                   -> the first 20 animals
#   GET /animals?species=parrot    -> 4 parrots
#   GET /animals?owner_id=1        -> owner 1's 2 animals
#   GET /animals?species=dog&limit=5 -> the first 5 dogs
#
# Every query parameter is optional: species and owner_id narrow the list
# only when they are given, and limit defaults to 20. Order by pet_id.
# --------------------------------------------------------------------------

# TODO: Problem 2


# --------------------------------------------------------------------------
# Problem 3. One owner's animals, in alphabetical order by name.
#
#   GET /owners/1/animals    -> Michele, then Zachary
#   GET /owners/999/animals  -> 404 with the detail "Owner not found"
#
# An owner who exists but has no animals gets 200 and [], not a 404:
# the owner was found, and the true answer is an empty list. (Every owner
# in vet.db has an animal, but the owners you add in Problem 5 do not.)
# --------------------------------------------------------------------------

# TODO: Problem 3


# ==========================================================================
# Part 2: request and response models (Nov 12)
#
# A class without table=True describes the shape of a request or a response,
# not a table. Write each class exactly as its problem describes, since the
# tests check the field names.
# ==========================================================================

# --------------------------------------------------------------------------
# Problem 4. One owner, without the address.
#
#   GET /owners/1    -> {"owner_id": 1, "name": "Holly Cruz", "num_animals": 2}
#   GET /owners/999  -> 404 with the detail "Owner not found"
#
# Write a class OwnerPublic with the fields owner_id (int), name (str), and
# num_animals (int), and declare it as the return type. A home address is
# not something a public endpoint should send, and the response model is
# what guarantees it never does: FastAPI sends only the declared fields.
#
# Count the animals in the database with func.count(), as in Problem 4 of
# practice_api.py, rather than loading every animal to count it in Python.
# --------------------------------------------------------------------------

# TODO: Problem 4


# --------------------------------------------------------------------------
# Problem 5. Add an owner.
#
#   POST /owners with {"name": "Pat Doe", "address": "1 Main St"}
#       -> 201 and {"owner_id": 21, "name": "Pat Doe", "num_animals": 0}
#   POST /owners with {"name": "Pat Doe"}  -> 201; the address is optional
#   POST /owners with {"address": "1 Main St"}  -> 422; the name is required
#   POST /owners with a name longer than 45 characters  -> 422
#
# Write a class OwnerCreate with name (required, at most 45 characters) and
# address (optional, at most 128 characters), using Field(max_length=...).
# It has no owner_id, since the database chooses the id. Return an
# OwnerPublic, and set the status code to 201 in the decorator.
#
# PetOwner.model_validate(data) makes a table object from an OwnerCreate.
# --------------------------------------------------------------------------

# TODO: Problem 5


# --------------------------------------------------------------------------
# Problem 6. Change some of an animal's fields.
#
#   PATCH /animals/1 with {"name": "Shelly"}
#       -> 200 and the animal, with only its name changed
#   PATCH /animals/1 with {"owner_id": 2}   -> 200, and animal 1 now belongs to owner 2
#   PATCH /animals/999 with {"name": "X"}   -> 404 with the detail "Animal not found"
#   PATCH /animals/1 with {"owner_id": 999} -> 409 with the detail "Owner not found"
#
# Write a class AnimalUpdate whose fields name, species, and owner_id are
# all optional, with a default of None. data.model_dump(exclude_unset=True)
# gives a dict of only the fields the client sent, and animal.sqlmodel_update()
# copies them onto the table object.
#
# The database rejects an owner_id that names no owner, and commit() raises
# IntegrityError. Catch it, roll back the session, and raise a 409.
# --------------------------------------------------------------------------

# TODO: Problem 6


# --------------------------------------------------------------------------
# Problem 7. Cancel an appointment.
#
#   DELETE /appointments/1    -> 204 with no body
#   DELETE /appointments/999  -> 404 with the detail "Appointment not found"
#
# Set the status code to 204 in the decorator, and return nothing.
# The rows of service_at_appt refer to the appointment, so delete them first,
# or the database will reject the delete and your endpoint will return 500.
# --------------------------------------------------------------------------

# TODO: Problem 7


# --------------------------------------------------------------------------
# Problem 8. Book an appointment.
#
#   POST /appointments with {"date_time": "2026-12-01T09:00:00", "appt_type": "exam",
#                            "reason": "limping", "pet_id": 1, "vet_id": 1}
#       -> 201 and the new appointment, including its appt_id
#   ... with "vet_id": 4      -> 422; employee 4 is a groomer, not a vet
#   ... with "pet_id": 999    -> 409; the database rejects the foreign key
#   ... at a date_time when that vet is already booked  -> 409
#
# Write a class AppointmentCreate with every column of Appointment except
# appt_id, and with the same types and defaults. Return an Appointment.
#
# In HW4 you found that no CHECK constraint can say that vet_id names a vet,
# because the rule involves another table. An endpoint can check it:
# if vet_id is given, the employee must exist and have emp_type 'vet', and
# likewise for groomer_id and 'groomer'. Otherwise raise a 422 with a detail
# that says which rule was broken.
#
# Every other mistake (a missing pet, a double booking, a grooming
# appointment with a vet) breaks a constraint in the database. Catch the
# IntegrityError, roll back, and raise a 409.
# --------------------------------------------------------------------------

# TODO: Problem 8
