# ═══════════════════════════════════════════════════════════════
# 🎮 Craft World - Economy - Utilitários
# 
# Desenvolvido por Plum com Qwen
# Telegram: @bondsbtc
# ═══════════════════════════════════════════════════════════════

import json
import logging
import os
from datetime import datetime
from config import *

def load_json_file(filepath):
    """Carrega arquivo JSON"""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        logging.warning(f"Arquivo não encontrado: {filepath}")
        return {}
    except json.JSONDecodeError as e:
        logging.error(f"Erro ao parsear JSON {filepath}: {e}")
        return {}

def save_json_file(filepath, data):
    """Salva arquivo JSON"""
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    with open(filepath, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)

def setup_logging(log_file, log_level='INFO'):
    """Configura logging"""
    os.makedirs(os.path.dirname(log_file), exist_ok=True)
    logging.basicConfig(
        filename=log_file,
        level=getattr(logging, log_level),
        format='%(asctime)s - %(levelname)s - %(message)s'
    )
    return logging.getLogger(__name__)

def get_language_config(language=None):
    """Obtém configuração de idioma"""
    if language is None:
        language = DEFAULT_LANGUAGE
    
    if language not in SUPPORTED_LANGUAGES:
        language = DEFAULT_LANGUAGE
    
    languages = load_json_file(LANGUAGES_FILE)
    return languages.get(language, languages.get(DEFAULT_LANGUAGE, {}))

def calculate_production_cost(resource, production_costs, market_prices):
    """Calcula custo de produção baseado nos inputs"""
    if resource in production_costs.get('factories', {}):
        cost_data = production_costs['factories'][resource]
        base_cost = cost_data.get('cost_usd', 0)
        
        if resource in market_prices:
            market_price = market_prices[resource].get('price_usd', 0)
            return min(base_cost, market_price) if market_price > 0 else base_cost
        return base_cost
    
    elif resource in production_costs.get('base_resources', {}):
        return production_costs['base_resources'][resource].get('cost_usd', 0)
    
    elif resource in production_costs.get('event_resources', {}):
        return production_costs['event_resources'][resource].get('cost_usd', 0)
    
    return 0

def format_number(value, decimals=8):
    """Formata números para exibição"""
    if value >= 1:
        return f"{value:.2f}"
    elif value >= 0.01:
        return f"{value:.4f}"
    else:
        return f"{value:.{decimals}f}"

def get_alert_emoji(priority):
    """Retorna emoji baseado na prioridade"""
    emojis = {
        'high': '🔴',
        'medium': '🟡',
        'low': '🔵'
    }
    return emojis.get(priority, '⚪')

def get_direction_emoji(direction):
    """Retorna emoji baseado na direção"""
    if 'COMPRA' in direction or 'BUY' in direction:
        return '📉'
    elif 'VENDA' in direction or 'SELL' in direction:
        return '📈'
    return '➡️'

def format_timestamp(timestamp, language='pt'):
    """Formata timestamp conforme idioma"""
    try:
        dt = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
        if language == 'pt':
            return dt.strftime('%d/%m/%Y %H:%M:%S')
        else:
            return dt.strftime('%Y-%m-%d %H:%M:%S')
    except:
        return timestamp[:19].replace('T', ' ')