import re
from urllib.parse import urlparse, urlunparse

from titlecase import titlecase


def parse_readcomicsonline_uri(uri: str) -> tuple:
    try:
        path = uri.split("comic/")[1]
    except IndexError:
        return "", "", ""

    parts = path.split("/")
    title = ""
    volume = 1
    page = 1
    if len(parts) == 2:
        title = titlecase(parts[0].replace("-", " "))
        volume = parts[1]
    if len(parts) == 3:
        title = titlecase(parts[0].replace("-", " "))
        volume = parts[1]
        page = parts[2]

    return title, volume, page


def get_comic_issue_url(url: str) -> str:
    parsed = urlparse(url)
    parts = [p for p in parsed.path.strip("/").split("/") if p]

    # Find the index of "comic"
    try:
        comic_index = parts.index("comic")
    except ValueError:
        raise ValueError("URL does not contain '/comic/' segment")

    # Extract title (next part after 'comic')
    if len(parts) <= comic_index + 1:
        raise ValueError("No comic title found after '/comic/'")
    title = parts[comic_index + 1]

    # Look for the first numeric segment after the title
    number = None
    for segment in parts[comic_index + 2 :]:
        if segment.isdigit():
            number = segment
            break

    # Build normalized path
    new_parts = ["comic", title]
    if number:
        new_parts.append(number)

    normalized_path = "/" + "/".join(new_parts)

    # Rebuild full URL (same scheme and host)
    simplified_url = urlunparse(
        parsed._replace(path=normalized_path, query="", fragment="")
    )
    return simplified_url
