import uuid
from typing import List, Optional

from sqlalchemy.orm import Session

from src.core.log_conf import logger
from src.db.models.comic import Artist
from src.schema.comics.artist import AddArtist
from src.schema.comics.artist_details import ArtistDetailResponse, ArtistWorktypeComicResponse, ArtistWorktypeIssueResponse
from src.schema.comics.comic import ComicResponse
from src.schema.comics.worktype import WorktypeResponse


def get_artist_details(artist: Artist) -> ArtistDetailResponse:
    comic_works: List[ArtistWorktypeComicResponse] = []
    comic_works_map = {}
    for work in artist.comic_works:
        worktype_id = work.work_type.id
        if worktype_id in comic_works_map:
            comic = ComicResponse(id=work.comic.id, title=work.comic.title, completed=work.comic.completed)
            comic_works_map[worktype_id].comics.append(comic)
        else:
            comic_works_map[worktype_id] = ArtistWorktypeComicResponse(
                worktype=WorktypeResponse(id=worktype_id, name=work.work_type.name),
                comics=[ComicResponse(id=work.comic.id, title=work.comic.title, completed=work.comic.completed)]
            )
    for value in comic_works_map.values():
        comic_works.append(value)
    issue_works: List[ArtistWorktypeIssueResponse] = []
    response = ArtistDetailResponse(
        id=artist.id,
        name=str(artist.name),
        weblink=str(artist.weblink),
        comic_works=comic_works,
        issue_works=issue_works,
    )
    return response

def update_artist(add_artist: AddArtist, artist_id: str, db: Session) -> Optional[Artist]:
    logger.info("update artist")
    artist: Optional[Artist] = db.get(Artist, artist_id)
    if artist is not None:
        artist.name = add_artist.name
        db.add(artist)
        db.commit()
        db.refresh(artist)
    return artist
