from typing import List
from fastapi import APIRouter, HTTPException, status

from src.apis.utils import SessionDep
from src.core.log_conf import logger
from src.db.repository.comics.artist import get_artist_details
from src.db.repository.comics.comic import get_comic_details, get_short_info, list_comics, get_issue_details
from src.schema.comics.artist_details import ArtistDetailResponse
from src.schema.comics.comic import ComicResponse 
from src.schema.comics.artist import ArtistCreation, ArtistResponse
from src.db.models.comic import Comic, Artist, Issue
from src.schema.comics.comic_details import ComicDetailsResponse
from src.schema.comics.issue_details import IssueDetailsResponse

router = APIRouter()


@router.get("/comics")
def get_all_comics(db: SessionDep) -> List[ComicResponse]:
    results: List[ComicResponse] = []
    comics = list_comics(db)
    for comic in comics:
        response = get_short_info(comic)
        results.append(response)
    return results

@router.get("/comics/{comic_id}", response_model=ComicDetailsResponse)
def get_comic(comic_id: str, db: SessionDep) -> ComicDetailsResponse:
    comic = db.get(Comic, comic_id)
    if comic is None:
        raise HTTPException(status_code=404, detail="Comic could not be found")
    logger.info(f"create ComicDetailsResponse for {comic}")
    response: ComicDetailsResponse = get_comic_details(comic)
    logger.info(f"ComicDetailsResponse: {response}")
    return response

@router.get("/artists", response_model=List[ArtistResponse])
def get_all_artists(db: SessionDep) -> List[ArtistResponse]:
    results: List[ArtistResponse] = []
    artists = db.query(Artist).all()
    for artist in artists:
        results.append(ArtistResponse(id=artist.id, name=str(artist.name)))
    return results

@router.get("/artists/{artist_id}", response_model=ArtistDetailResponse)
def get_artist(artist_id: str, db: SessionDep) -> ArtistDetailResponse:
    artist = db.get(Artist, artist_id)
    if artist is None:
        raise HTTPException(status_code=404, detail="Artist could not be found")
    response: ArtistDetailResponse = get_artist_details(artist)
    return response

@router.post("/artists", status_code=status.HTTP_201_CREATED)
def add_artist(db: SessionDep, artist_creation: ArtistCreation) -> ArtistResponse:
    artist: Artist = Artist()
    setattr(artist, "name", artist_creation.name)
    try:
        db.add(artist)
        db.commit()
    except:
        raise HTTPException(status_code=409, detail="Artist already added")
    response = ArtistResponse(id=artist.id, name=str(artist.name))
    return response

@router.get("/issues", response_model=List[IssueDetailsResponse])
def get_issues(db: SessionDep) -> List[IssueDetailsResponse]:
    results: List[IssueDetailsResponse] = []
    issues = db.query(Issue).all()
    for issue in issues:
        results.append(get_issue_details(issue))
    return results
