import requests
from misskey.exceptions import MisskeyAPIException
from client import client_connection
from db_utils import insert_character
from custom_types import Character
from config import RARITY_TO_WEIGHT


def add_character(
        name: str,
        rarity: int,
        image_url: str) -> tuple[int, str]:
    '''
    Adds a character to the database, uploading the image from a public URL to
    the bot's Misskey Drive.

    Args:
        name (str): Character name.
        rarity (int): Character rarity (e.g., 1-5).
        image_url (str): Public URL of the image from the post (e.g., from
            note['files'][i]['url']).

    Returns:
        tuple[int, str]: Character ID and bot's Drive file_id.

    Raises:
        ValueError: If inputs are invalid.
        RuntimeError: If image download/upload or database operation fails.
    '''

    stripped_name = name.strip()

    # Validate inputs
    if not stripped_name:
        raise ValueError('Character name cannot be empty.')
    if rarity < 1:
        raise ValueError('Rarity must be a positive integer.')
    if rarity not in RARITY_TO_WEIGHT.keys():
        raise ValueError(f'Invalid rarity: {rarity}')
    if not image_url:
        raise ValueError('Image URL must be provided.')

    # Download image
    response = requests.get(image_url, stream=True, timeout=30)
    if response.status_code != 200:
        raise RuntimeError(f'Failed to download image from {image_url}')

    # Upload to bot's Drive
    mk = client_connection()
    try:
        media = mk.drive_files_create(response.raw)
        file_id = media['id']
    except MisskeyAPIException as e:
        raise RuntimeError(f'Failed to upload image to bot\'s Drive: {e}')\
                from e

    # Insert into database
    character_id = insert_character(
            stripped_name,
            rarity,
            RARITY_TO_WEIGHT[rarity],
            file_id
    )
    return character_id, file_id