from typing import List, Dict, Optional

from pydantic import BaseModel, AnyUrl

from src.db.models.comic import Comic


class ComicResponse(BaseModel):
    id: str
    title: str
    completed: bool

class ComicDetailsResponse(BaseModel):
    id: str
    created: str
    title: str
    completed : bool
    current_order : bool
    weblink: str
    publisher: str
    volumes: List[str]
    works: Dict[str, List[str]]


class ComicSchema(BaseModel):
    id: str
    title: str
    weblink: Optional[AnyUrl]
    completed: Optional[bool]
    current_order: Optional[bool]


def get_short_info(comic: Comic) -> ComicResponse:
    response = ComicResponse(
        id=comic.id,
        title=comic.title,
        completed=(comic.completed == 1)
    )
    return response


def get_comic_details(comic: Comic) -> ComicDetailsResponse | None:
    volumes = []
    for volume in comic.volumes:
        volumes.append(volume.name)
    works = {}
    for work in comic.comic_works:
        work_type = work.work_type.name
        artist_name = work.artist.name
        if work_type in works:
            works[work_type].append(artist_name)
        else:
            works[work_type] = [artist_name]
    response = ComicDetailsResponse(
        id=comic.id,
        created=str(comic.created_date),
        title=comic.title,
        completed=comic.completed,
        current_order=comic.current_order,
        weblink=comic.weblink,
        publisher=comic.publisher.name,
        volumes=volumes,
        works=works
    )
    return response
