from typing import Dict, List, Optional

from sqlalchemy.orm import Session

from src.core.log_conf import logger
from src.db.models.comic import Comic, Issue
from src.schema.comics.artist import artist_to_response
from src.schema.comics.comic import ComicSchema, comic_to_response
from src.schema.comics.comic_details import ComicDetailsResponse, ComicWorktypeArtistResponse
from src.schema.comics.issue import IssueResponse, issue_to_response
from src.schema.comics.issue_details import IssueDetailsResponse
from src.schema.comics.publisher import publisher_to_response
from src.schema.comics.volume import VolumeResponse, volume_to_response
from src.schema.comics.worktype import worktype_to_response


def get_issue_details(issue: Issue) -> IssueDetailsResponse:
    volume = None
    if issue.volume:
        volume = volume_to_response(issue.volume)
    response = IssueDetailsResponse(
        id=issue.id,
        issue_number=str(issue.issue_number),
        in_stock=bool(issue.in_stock),
        is_read=bool(issue.is_read),
        comic=comic_to_response(issue.comic),
        volume=volume
    )
    return response


def update_comic(new_comic: ComicSchema, comic_id: str, db: Session) -> Optional[Comic]:
    logger.info(f"update_comic: {new_comic} with {comic_id}")
    comic: Optional[Comic] = db.get(Comic, comic_id)
    return comic

def get_comic_details(comic: Comic) -> ComicDetailsResponse:
    volumes: List[VolumeResponse] = []
    for volume in comic.volumes:
        volumes.append(volume_to_response(volume))
    issues: List[IssueResponse] = []
    for issue in comic.issues:
        issues.append(issue_to_response(issue))
    works: List[ComicWorktypeArtistResponse] = []
    works_map: Dict[str, ComicWorktypeArtistResponse] = {}
    for work in comic.comic_works:
        worktype_id = work.work_type.id
        if worktype_id in works_map:
            artist = artist_to_response(work.artist)
            works_map[worktype_id].artists.append(artist)
            logger.info(f"add artist to response map: {artist} -> {works_map}")
            print(f"add artist to response map: {artist} -> {works_map}")
        else:
            works_map[worktype_id] = ComicWorktypeArtistResponse(
                worktype=worktype_to_response(work.work_type),
                artists=[artist_to_response(work.artist)]
            )
    for value in works_map.values():
        works.append(value)
    response = ComicDetailsResponse(
        id=str(comic.id),
        created=str(comic.created_date),
        title=str(comic.title),
        completed=bool(comic.completed),
        current_order=bool(comic.current_order),
        weblink=str(comic.weblink),
        publisher=publisher_to_response(comic.publisher),
        issues=issues,
        volumes=volumes,
        works=works
    )
    return response
