from __future__ import annotations
import json, sqlite3
from typing import Any


def setting(c: sqlite3.Connection, key: str, default: str = '') -> str:
    try:
        row=c.execute('SELECT value FROM settings WHERE key=?',(key,)).fetchone()
        return str(row['value'] if row else default)
    except sqlite3.Error:
        return default


def setting_int(c: sqlite3.Connection, key: str, default: int) -> int:
    try: return int(setting(c,key,str(default)))
    except (TypeError,ValueError): return default


def setting_bool(c: sqlite3.Connection, key: str, default: bool=False) -> bool:
    return setting(c,key,'1' if default else '0').strip().lower() in {'1','true','yes','on','evet'}


def log_event(c: sqlite3.Connection, process: str, level: str, message: str, *, run_type: str|None=None,
              run_id: int|None=None, product_id: int|None=None, source_id: int|None=None,
              merchant_id: int|None=None, details: dict[str,Any]|None=None, commit: bool=False) -> None:
    try:
        payload=json.dumps(details or {},ensure_ascii=False,separators=(',',':')) if details else None
        c.execute('''INSERT INTO operation_logs(level,process,run_type,run_id,product_id,source_id,merchant_id,message,details_json)
                     VALUES(?,?,?,?,?,?,?,?,?)''',
                  (level[:16],process[:48],run_type,run_id,product_id,source_id,merchant_id,str(message)[:2000],payload))
        if commit: c.commit()
    except sqlite3.Error:
        # Loglama ana işi hiçbir zaman durdurmamalı.
        pass
