import sys
import logging
import json
from pathlib import Path
from datetime import datetime, date
from typing import List, Dict, Optional, Union, Any
log_file_path = Path.home() / "Documents" / "JewelerAppLogs" / "app.log"
# Logging Ayarları (Aynen kalabilir, sadece path yukarıda güncellendi)
handlers = [logging.StreamHandler(sys.stdout)]
try:
    handlers.insert(0, logging.FileHandler(log_file_path, encoding='utf-8'))
except Exception:
    pass

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=handlers,
)
logger = logging.getLogger(__name__)

APP_THEMES = {
    "Green Harmony": {
        "primary": "#285430", "secondary": "#5F8D4E", "background": "#F1F8E9",
        "text_dark": "#000000", "text_light": "#FFFFFF", "danger": "#D32F2F",
        "warning": "#FFC107",
    },
    "Modern Dark Gold": {
        "primary": "#D4AF37",
        "secondary": "#4F4F4F",
        "background": "#212121",
        "background_alt": "#333333",
        "text_dark": "#FFFFFF",
        "text_light": "#FFFFFF",
        "tertiary": "#6E6E6E",
        "border": "#555555",
        "danger": "#CF6679",
        "warning": "#FFCA28",
    },
    "Ocean Blue": {
        "primary": "#0D47A1", "secondary": "#1976D2", "background": "#E3F2FD",
        "text_dark": "#000000", "text_light": "#FFFFFF", "danger": "#D32F2F",
        "warning": "#FFC107",
    },
    "Royal Purple": {
        "primary": "#4A148C", "secondary": "#7B1FA2", "background": "#F3E5F5",
        "text_dark": "#000000", "text_light": "#FFFFFF", "danger": "#D32F2F",
        "warning": "#FFC107",
    },
    "Ruby Red": {
        "primary": "#B71C1C", "secondary": "#D32F2F", "background": "#FFEBEE",
        "text_dark": "#000000", "text_light": "#FFFFFF", "danger": "#B71C1C",
        "warning": "#FFC107",
    },
    "Sunset Orange": {
        "primary": "#E65100", "secondary": "#F57C00", "background": "#FFF3E0",
        "text_dark": "#000000", "text_light": "#FFFFFF", "danger": "#D32F2F",
        "warning": "#E65100",
    },
    "Golden Sun": {
        "primary": "#F57F17", "secondary": "#FBC02D", "background": "#FFFDE7",
        "text_dark": "#000000", "text_light": "#000000",
        "danger": "#D32F2F", "warning": "#F57F17",
    },
    "Classic Dark": {
        "primary": "#212121", "secondary": "#424242", "background": "#303030",
        "text_dark": "#FFFFFF", "text_light": "#FFFFFF", "danger": "#E53935",
        "warning": "#FFB300",
    },
}
BASE_CURRENCY: str = "EUR"
SUPPORTED_CURRENCIES: List[str] = ["TRY", "USD", "EUR", "GBP"]
TRUNCGIL_API_URL: str = "https://golder.biz/kurlar/kurlar.json"
PROFILES_CONFIG_FILE: str = "profiles.json"
CUSTOM_THEMES_FILE: str = "custom_themes.json"
PROFILE_DATA_VERSION: float = 1.02
FONT_PATH: str = str(Path(__file__).resolve().parent / "Resources" / "DejaVuSans.ttf")
# --- MERKEZİ KLASÖR YAPILANDIRMASI ---
APP_DIR_NAME: str = "Golder"


APP_DATA_DIR = Path.home() / "Documents" / APP_DIR_NAME
APP_DATA_DIR.mkdir(parents=True, exist_ok=True)

# --- DİL (JSON) YÖNETİMİ ---
LANG_DIR = APP_DATA_DIR / "lang"
LANG_DIR.mkdir(parents=True, exist_ok=True)

class SafeLangDict(dict):
    """
    JSON içinde eksik bir kelime varsa programın çökmesini engeller.
    Eğer kelime yoksa, direkt olarak aranılan anahtarı (key) ekrana basar.
    """
    def __missing__(self, key):
        return key

def get_available_languages() -> list:
    """Belgeler/Golder/lang klasöründeki tüm .json dosyalarını tarar."""
    langs = []
    if LANG_DIR.exists():
        for file in LANG_DIR.glob("*.json"):
            langs.append(file.stem)

    if not langs:
        return ["TR"]
    return sorted(langs)

def load_language(lang_code: str) -> SafeLangDict:
    """Belirtilen JSON dosyasını okur ve Güvenli Sözlük olarak döndürür."""
    file_path = LANG_DIR / f"{lang_code}.json"
    lang_data = SafeLangDict()

    if file_path.exists():
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                data = json.load(f)
                lang_data.update(data)
        except Exception as e:
            logger.error(f"Dil dosyası okunamadı veya bozuk ({lang_code}.json): {e}")

    return lang_data

def get_active_language_code() -> str:
    """Aktif dil kodunu global ayarlardan döndürür."""
    return str(get_global_setting("language", "TR") or "TR").strip() or "TR"

def get_language_text(key: str, fallback: str = "", lang_code: Optional[str] = None) -> str:
    """Aktif veya belirtilen dil için güvenli çeviri döndürür."""
    value = str(load_language(lang_code or get_active_language_code()).get(key, fallback) or fallback).strip()
    return value or fallback

def get_language_aliases(key: str, fallback: str) -> List[str]:
    """
    Bir sistem adının tüm dil varyasyonlarını döndürür.
    Varsayılan depo/kasa gibi kayıtların dil değişince çoğalmamasını önler.
    """
    aliases: List[str] = []
    for code in get_available_languages() or ["TR"]:
        value = get_language_text(key, fallback, code)
        if value and value not in aliases:
            aliases.append(value)
    if fallback and fallback not in aliases:
        aliases.append(fallback)
    return aliases

def get_default_depot_name() -> str:
    return get_language_text("default_depot_name", "Merkez")

def get_default_cash_account_name() -> str:
    return get_language_text("default_cash_account_name", "Ana Kasa")

# Log Dosyası
log_file_path = APP_DATA_DIR / "app.log"

# Kaynaklar (Resimler vs.)
RESOURCES_DIR = APP_DATA_DIR / "Resources"
RESOURCES_DIR.mkdir(parents=True, exist_ok=True)

# MariaDB Klasörü (Embedded DB için)
MARIADB_DIR = APP_DATA_DIR / "mariadb"

# Font Dosyası (Doğrudan Golder klasöründe aranacak)
FONT_PATH = str(APP_DATA_DIR / "DejaVuSans.ttf")

# Logo Dosyası (Doğrudan Golder klasöründe aranacak)
LOGO_PATH = APP_DATA_DIR / "golder.png"

# Profil Dosyaları
PROFILES_CONFIG_FILE: str = "profiles.json"
CUSTOM_THEMES_FILE: str = "custom_themes.json"


def get_global_setting(key: str, default: Any = None) -> Any:
    file_path = APP_DATA_DIR / "global_settings.json"
    if not file_path.exists(): return default
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            data = json.load(f)
            return data.get(key, default)
    except: return default

def set_global_setting(key: str, value: Any) -> None:
    file_path = APP_DATA_DIR / "global_settings.json"
    data = {}
    if file_path.exists():
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                data = json.load(f)
        except: pass
    data[key] = value
    try:
        with open(file_path, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
    except: pass

def get_app_data_directory() -> str:
    """Doğrudan yapılandırılmış yolu döndürür."""
    return str(APP_DATA_DIR)
def get_mono_font() -> str:
    """Returns a monospace font name suitable for the current operating system."""
    return "Consolas" if sys.platform == "win32" else "Courier"
def format_date_for_display(iso_date_str: str) -> str:
    """Converts an ISO formatted datetime string to 'DD.MM.YYYY' format."""
    try:
        return datetime.fromisoformat(iso_date_str).strftime("%d.%m.%Y")
    except (ValueError, TypeError):
        return iso_date_str
def parse_date_from_display(date_str: Any) -> Optional[datetime]:
    """
    Tarih string'ini datetime'a çevirir.
    Desteklenen formatlar:
    - 'DD.MM.YYYY'
    - 'DD.MM.YYYY HH:MM'
    - 'DD.MM.YYYY HH:MM:SS'
    - ISO 8601 (örn: 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS', 'YYYY-MM-DDTHH:MM:SS[.ffffff][Z]')
    """
    if date_str is None:
        return None
    if isinstance(date_str, datetime):
        return date_str
    if isinstance(date_str, date):
        return datetime.combine(date_str, datetime.min.time())
    try:
        s = str(date_str).strip()
    except Exception:
        return None
    if not s:
        return None
    for fmt in ("%d.%m.%Y %H:%M:%S", "%d.%m.%Y %H:%M", "%d.%m.%Y"):
        try:
            return datetime.strptime(s, fmt)
        except ValueError:
            pass
    try:
        return datetime.fromisoformat(s.replace("Z", ""))
    except (ValueError, TypeError):
        return None
def format_number(num: Union[int, float], precision: int = 2) -> str:
    """Formats a number, removing trailing .00 for integers."""
    try:
        if num == int(num) and precision == 2:
             return f"{int(num):,}"
        return f"{num:,.{precision}f}"
    except (ValueError, TypeError):
        return "0"
SUB_TAB_PERMISSIONS = {
    "cat_shopping": {
        "perm_product_purchase": "Altın Alış",
        "perm_product_sale": "Altın Satış",
        "perm_scrap_purchase": "Hurda Alış",
        "perm_scrap_sale": "Hurda Satış",
        "perm_ziynet_purchase": "Ziynet Alış",
        "perm_ziynet_sale": "Ziynet Satış",
    },
    "cat_finance": {
        "perm_add_income": "Gelir Ekle",
        "perm_add_expense": "Gider Ekle",
        "perm_transfer": "Hesaplar Arası Transfer",
        "perm_scheduled": "Vadeli İşlemler",
        "perm_cash_view": "Nakit Kasalar (Görüntüleme)",
        "perm_card_view": "Kart Hesapları (Görüntüleme)",
        "perm_exchange": "Döviz İşlemleri",
    },
    "cat_stocks": {
        "perm_stock_product": "Altın Stoğu",
        "perm_def_product": "Altın Tanımlama",
        "perm_stock_scrap": "Hurda Stoğu",
        "perm_def_scrap": "Hurda Tanımlama",
        "perm_stock_ziynet": "Ziynet Stoğu",
        "perm_def_ziynet": "Ziynet Tanımlama",
        "perm_depots": "Depolar (Yönetim & Özet)",
    },
    "cat_crm": {
        "perm_accounts": "Cari Hesaplar (Borç/Alacak)",
        "perm_contacts": "Müşteri Yönetimi (Kişi Ekle/Sil)",
    },
    "cat_services": {
        "perm_repair": "Tamir Takip",
        "perm_services": "Hizmetler (Diğer)",
    },
    "cat_tools": {
        "perm_reports": "Raporlama",
        "perm_agenda": "Ajanda",
        "perm_search": "Arama / Barkod Sorgu",
        "perm_calculator": "Hesap Makinesi",
        "perm_zakat": "Zekat Hesaplama (Mağaza)",
        "perm_zakat_guest": "Zekat Hesaplama (Müşteri)"
    }
}




