# Kemoverse - a gacha-style bot for the Fediverse.
# Copyright © 2025 Waifu, Moon, VD15 and contributors.

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see https://www.gnu.org/licenses/.

import requests
import config
from fediverse_factory import get_fediverse_service
import db_utils

def add_card(name: str, rarity: int, image_url: str, power: int, charm: int, wit: int) -> tuple[int, str]:
    """
    Adds a card to the database, uploading the image from a public URL to the Fediverse instance.

    Args:
        name (str): Card name.
        rarity (int): Card rarity (e.g., 1-5).
        image_url (str): Public URL of the image from the post.
        power (int): Card power value.
        charm (int): Card charm value.
        wit (int): Card wit value.

    Returns:
        tuple[int, str]: Card ID and 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('Card name cannot be empty.')
    if rarity < 1:
        raise ValueError('Rarity must be a positive integer.')
    if rarity not in config.RARITY_TO_WEIGHT.keys():
        raise ValueError(f'Invalid rarity: {rarity}')
    if not image_url:
        raise ValueError('Image URL must be provided.')
    if power < 0 or charm < 0 or wit < 0:
        raise ValueError('Power, charm, and wit must be non-negative integers.')
    try:
        # 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 Fediverse instance
        fediverse_service = get_fediverse_service(config.INSTANCE_TYPE)
        try:
            uploaded_file = fediverse_service.upload_file(response.raw)
            file_id = uploaded_file.id
        except RuntimeError as e:
            raise RuntimeError(f"Failed to upload image: {e}") from e

        # Insert into database using db_utils function
        card_id = db_utils.insert_card(
            stripped_name,
            rarity,
            file_id,
            power,
            charm,
            wit
        )
        
        return card_id, file_id

    except Exception as e:
        raise
