import os
from datetime import datetime

import xbmcvfs


def _safe_debug_log_write(debug_log_path, message):
    try:
        with open(debug_log_path, "a", encoding='utf-8') as debug_file:
            debug_file.write(f"{message}\n")
    except Exception:
        pass


def update_program_info_properties(window, addon, program, channel):
    """Write selected-program properties to EPG window."""
    profile_path = xbmcvfs.translatePath(addon.getAddonInfo('profile'))
    debug_log_path = os.path.join(profile_path, "debug_log.txt")
    try:
        if not xbmcvfs.exists(profile_path):
            xbmcvfs.mkdirs(profile_path)
    except Exception:
        debug_log_path = xbmcvfs.translatePath("special://temp/debug_log.txt")

    _safe_debug_log_write(debug_log_path, f"\n\nUpdating program info at {datetime.now()}")

    if program:
        _safe_debug_log_write(
            debug_log_path,
            f"Program: {program.get('title', 'Unknown').encode('utf-8', 'ignore').decode('utf-8')}",
        )
        _safe_debug_log_write(debug_log_path, f"Available keys: {', '.join(program.keys())}")

        title = program.get('title', 'Unknown').encode('utf-8', 'ignore').decode('utf-8')
        if program.get('sub_title'):
            title = f"{title} - {program['sub_title']}"
        window.setProperty('ProgramTitle', title)

        start_time = window.format_time(program['start']) if 'start' in program else 'Unknown'
        end_time = window.format_time(program['stop']) if 'stop' in program else 'Unknown'
        window.setProperty('ProgramTime', f"{start_time} - {end_time}")

        if channel:
            window.setProperty('ProgramChannel', f"{channel.get('name', 'Unknown')} (Channel {channel.get('tvg_id', '')})")
        else:
            window.setProperty('ProgramChannel', program.get('channel', 'Unknown'))

        sports_icon = ['soccer', 'football', 'basketball', 'hockey', 'baseball', 'tennis']
        default_icon = 'special://home/addons/plugin.video.jet_guide/resources/skins/default/720p/media/HDHR.png'
        default_sports_icon = 'special://home/addons/plugin.video.jet_guide/resources/skins/default/720p/media/sports_icon.png'
        if any(sport in title.lower() for sport in sports_icon):
            default_icon = default_sports_icon
        icon_url = channel.get('logo', default_icon) if channel else default_icon
        _safe_debug_log_write(debug_log_path, f"Using icon: {icon_url}")
        window.setProperty('ProgramIcon', icon_url)

        desc = program.get('desc', 'No description available').encode('utf-8', 'ignore').decode('utf-8')
        if program.get('actors'):
            desc += f"\n\nActors: {', '.join(program['actors'])}"
        if program.get('rating'):
            desc += f"\nRating: {program['rating']}"
        if program.get('category'):
            if isinstance(program['category'], list):
                desc += f"\nCategory: {', '.join(program['category'])}"
            else:
                desc += f"\nCategory: {program['category']}"
        if program.get('episode'):
            desc += f"\nEpisode: {program['episode']}"
        window.setProperty('ProgramDescription', desc)
    else:
        _safe_debug_log_write(debug_log_path, "No program provided, setting default properties")
        window.setProperty('ProgramTitle', 'No Program')
        window.setProperty('ProgramTime', '')
        window.setProperty('ProgramChannel', channel.get('name', 'Unknown') if channel else 'Unknown')
        window.setProperty('ProgramIcon', 'special://home/addons/plugin.video.jet_guide/resources/skins/default/720p/media/HDHR.png')
        window.setProperty('ProgramDescription', 'No program information available.')

    _safe_debug_log_write(debug_log_path, "Program info update complete")
