# Updated font loading and color scheme for Progression Loader
# Steam Collections page inspired design:
# - Dark blue theme matching Steam's signature colors
# - Steam blue (#66c0f4) for highlights and accents
# - Dark blue backgrounds (#1b2838, #2a475e) for depth
# - Light blue-gray text (#c7d5e0) for readability
# - Card-based layouts with rounded corners
# - Subtle shadows and glows for depth

import os
import sys
from pathlib import Path

def get_resource_path(relative_path):
    """Get absolute path to resource, works for dev and for PyInstaller"""
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    
    return os.path.join(base_path, relative_path)

# Steam Collections inspired color constants
COLORS = {
    'bg_primary': '#1b2838',        # Steam dark blue background
    'bg_secondary': '#2a475e',      # Steam medium blue background
    'bg_tertiary': '#1e2328',       # Steam darker background for cards
    'bg_card': '#16202d',           # Steam card background
    'bg_hover': '#2a475e',          # Steam hover state
    'text_primary': '#c7d5e0',      # Steam primary text (light blue-gray)
    'text_highlight': '#66c0f4',    # Steam blue highlight color
    'text_body': '#8f98a0',         # Steam body text (muted blue-gray)
    'text_secondary': '#acb2b8',    # Steam secondary text
    'text_muted': '#67707b',        # Steam muted text
    'accent_green': '#5ba32b',      # Steam success green
    'accent_red': '#cd5c5c',        # Steam error red
    'accent_yellow': '#ffa500',     # Steam warning orange
    'accent_blue': '#66c0f4',       # Steam signature blue
    'border_light': '#3c4043',      # Steam light border
    'border_dark': '#0e141b',       # Steam dark border
}

def load_all_georgia_fonts():
    """Load all Georgia font variants using Windows AddFontResourceEx with private flag"""
    custom_font_available = False
    custom_font_family = None
    
    # List of Georgia font files to load
    georgia_fonts = [
        "georgia.ttf",      # Regular
        "georgiab.ttf",     # Bold
        "georgiai.ttf",     # Italic
        "georgiaz.ttf"      # Bold Italic
    ]
    
    fonts_loaded = 0
    
    try:
        for font_file in georgia_fonts:
            font_path = get_resource_path(os.path.join("art", font_file))
            if os.path.exists(font_path):
                abs_font_path = os.path.abspath(font_path)
                
                # Use the Stack Overflow method with AddFontResourceEx
                success = _load_font_private(abs_font_path)
                
                if success:
                    fonts_loaded += 1
                    print(f"Successfully loaded font: {font_file}")
                else:
                    print(f"Failed to load font: {font_file}")
            else:
                print(f"Font file not found: {font_path}")
        
        if fonts_loaded > 0:
            custom_font_available = True
            custom_font_family = "Georgia"
            print(f"Successfully loaded {fonts_loaded} Georgia font variants")
        else:
            print("No Georgia fonts could be loaded, using system fallback")
            
    except Exception as e:
        print(f"Error loading fonts: {e}")
        custom_font_available = False
        custom_font_family = None
    
    return custom_font_available, custom_font_family

def _load_font_private(fontpath):
    """
    Load font privately using AddFontResourceEx
    Based on Stack Overflow solution by Felipe
    """
    try:
        from ctypes import windll, byref, create_unicode_buffer
        
        # Constants for AddFontResourceEx
        FR_PRIVATE = 0x10   # Font is private to this process
        FR_NOT_ENUM = 0x20  # Font won't appear in font enumeration
        
        # Create unicode buffer for the font path
        pathbuf = create_unicode_buffer(fontpath)
        
        # Use AddFontResourceExW for Unicode strings
        AddFontResourceEx = windll.gdi32.AddFontResourceExW
        
        # Set flags: private (unloaded when process dies) and not enumerable
        flags = FR_PRIVATE | FR_NOT_ENUM
        
        # Add the font resource
        numFontsAdded = AddFontResourceEx(byref(pathbuf), flags, 0)
        
        return numFontsAdded > 0
        
    except Exception as e:
        print(f"Error in _load_font_private: {e}")
        return False

def apply_steam_styling():
    """Apply Steam Collections page inspired styling to UI components"""
    return {
        'button_style': {
            'relief': 'flat',
            'borderwidth': 0,
            'highlightthickness': 0,
            'font': ('Georgia', 10, 'bold'),
            'cursor': 'hand2'
        },
        'entry_style': {
            'relief': 'flat',
            'borderwidth': 2,
            'highlightthickness': 0,
            'font': ('Georgia', 9),
            'insertbackground': COLORS['text_primary']
        },
        'label_style': {
            'font': ('Georgia', 9),
            'anchor': 'w'
        },
        'title_style': {
            'font': ('Georgia', 14, 'bold'),
            'anchor': 'center'
        },
        'card_style': {
            'relief': 'flat',
            'borderwidth': 1,
            'highlightthickness': 0
        }
    }

def get_steam_button_colors(button_type='default'):
    """Get Steam-inspired button color schemes"""
    button_colors = {
        'default': {
            'bg': COLORS['bg_secondary'],
            'fg': COLORS['text_primary'],
            'activebackground': COLORS['bg_hover'],
            'activeforeground': COLORS['text_highlight']
        },
        'primary': {
            'bg': COLORS['accent_blue'],
            'fg': COLORS['bg_primary'],
            'activebackground': COLORS['text_highlight'],
            'activeforeground': COLORS['bg_primary']
        },
        'success': {
            'bg': COLORS['accent_green'],
            'fg': COLORS['text_primary'],
            'activebackground': '#6bb33f',
            'activeforeground': COLORS['text_primary']
        },
        'warning': {
            'bg': COLORS['accent_yellow'],
            'fg': COLORS['bg_primary'],
            'activebackground': '#ffb733',
            'activeforeground': COLORS['bg_primary']
        },
        'danger': {
            'bg': COLORS['accent_red'],
            'fg': COLORS['text_primary'],
            'activebackground': '#d66f6f',
            'activeforeground': COLORS['text_primary']
        }
    }
    
    return button_colors.get(button_type, button_colors['default'])