"""DM Schema V1/V2 Converter Utility Functions."""

import random
import string
from typing import Any

from .types import MEDIA_TYPE_MAP, MEDIA_TYPE_REVERSE_MAP


def generate_random_id(length: int = 10) -> str:
    """Generate a random ID compatible with V1 format."""
    chars = string.ascii_letters + string.digits
    return ''.join(random.choice(chars) for _ in range(length))


def extract_media_type_info(media_id: str) -> tuple[str, str]:
    """Extract type information from media ID.

    Args:
        media_id: Media ID (e.g., 'image_1', 'video_2')

    Returns:
        (singular, plural) tuple (e.g., ('image', 'images'))
    """
    for media_type in MEDIA_TYPE_MAP:
        if media_id.startswith(media_type):
            return media_type, MEDIA_TYPE_MAP[media_type]
    raise ValueError(f'Unknown media type: {media_id}')


def detect_file_type(data: dict[str, Any], is_v2: bool = False) -> str:
    """Auto-detect file type from data."""
    if is_v2:
        check_data = data.get('annotation_data', data)
        for plural_type in MEDIA_TYPE_REVERSE_MAP:
            if plural_type in check_data and check_data[plural_type]:
                return MEDIA_TYPE_REVERSE_MAP[plural_type]
    else:
        for key in ['annotations', 'annotationsData']:
            if key in data and data[key]:
                first_media_id = next(iter(data[key].keys()), None)
                if first_media_id:
                    singular, _ = extract_media_type_info(first_media_id)
                    return singular
    raise ValueError('Unable to detect file type')


def get_attr_value(attrs: list[dict[str, Any]], name: str, default: Any = None) -> Any:
    """Extract value for a specific name from attrs list."""
    for attr in attrs:
        if attr.get('name') == name:
            return attr.get('value', default)
    return default


def set_attr_value(attrs: list[dict[str, Any]], name: str, value: Any) -> list[dict[str, Any]]:
    """Add or update attribute in attrs list."""
    for attr in attrs:
        if attr.get('name') == name:
            attr['value'] = value
            return attrs
    attrs.append({'name': name, 'value': value})
    return attrs
