from typing import Optional

def get_clean_kana(_s):
    return _s.strip(" \n\t\r").replace("  ", " ").replace("  ", " ").replace("  ", " ")

def japanese_to_kana(text: str, katakana: bool = False) -> str:
    try:
        import pykakasi
    except ImportError:
        raise ImportError(
            "pykakasi is required for Japanese to kana conversion. "
            "Install it with: pip install pykakasi --break-system-packages"
        )

    kks = pykakasi.kakasi()
    result = kks.convert(text)

    kana_key = 'kana' if katakana else 'hira'
    kana_parts = [item[kana_key] if kana_key in item else item.get('orig', '') 
                  for item in result]
    kana_text = ''.join(kana_parts)
    
    return get_clean_kana(kana_text)

def japanese_to_kana_mixed(text: str) -> str:
    try:
        import pykakasi
    except ImportError:
        raise ImportError(
            "pykakasi is required for Japanese to kana conversion. "
            "Install it with: pip install pykakasi --break-system-packages"
        )

    kks = pykakasi.kakasi()
    result = kks.convert(text)

    kana_parts = []
    for item in result:
        orig = item.get('orig', '')
        
        if all('\u3040' <= c <= '\u309F' for c in orig if c.strip()):
            kana_parts.append(orig)
        elif all('\u30A0' <= c <= '\u30FF' for c in orig if c.strip()):
            kana_parts.append(orig)
        else:
            kana_parts.append(item.get('hira', orig))
    
    kana_text = ''.join(kana_parts)
    return get_clean_kana(kana_text)

def japanese_to_kana_spaced(text: str, katakana: bool = False) -> str:
    try:
        import pykakasi
    except ImportError:
        raise ImportError(
            "pykakasi is required. Install with: pip install pykakasi --break-system-packages"
        )
    
    kks = pykakasi.kakasi()
    result = kks.convert(text)
    
    kana_key = 'kana' if katakana else 'hira'
    kana_parts = []
    for item in result:
        kana = item[kana_key] if kana_key in item else item.get('orig', '')
        kana_parts.append(get_clean_kana(kana))
    
    return ' '.join(kana_parts)

def japanese_to_kana_mixed_spaced(text: str) -> str:
    try:
        import pykakasi
    except ImportError:
        raise ImportError(
            "pykakasi is required. Install with: pip install pykakasi --break-system-packages"
        )
    
    kks = pykakasi.kakasi()
    result = kks.convert(text)
    
    kana_parts = []
    for item in result:
        orig = item.get('orig', '')

        if all('\u3040' <= c <= '\u309F' for c in orig if c.strip()):
            kana = orig
        elif all('\u30A0' <= c <= '\u30FF' for c in orig if c.strip()):
            kana = orig
        else:
            kana = item.get('hira', orig)
        
        kana_parts.append(get_clean_kana(kana))
    
    return ' '.join(kana_parts)
