import logging
import os
from pathlib import Path

DB_PATH = Path(os.getenv("DB_NAME", "owlynews.sqlite3"))
OLLAMA_HOST = os.getenv("OLLAMA_HOST", "http://localhost:11434")
MIN_CRON_HOURS = float(os.getenv("MIN_CRON_HOURS", 0.5))
DEFAULT_CRON_HOURS = float(os.getenv("CRON_HOURS", MIN_CRON_HOURS))
CRON_HOURS = max(MIN_CRON_HOURS, DEFAULT_CRON_HOURS)
SYNC_COOLDOWN_MINUTES = int(os.getenv("SYNC_COOLDOWN_MINUTES", 30))
LLM_MODEL = os.getenv("LLM_MODEL", "mistral-nemo:12b")
LLM_TIMEOUT_SECONDS = int(os.getenv("LLM_TIMEOUT_SECONDS", 180))
OLLAMA_API_TIMEOUT_SECONDS = int(os.getenv("OLLAMA_API_TIMEOUT_SECONDS", 10))
ARTICLE_FETCH_TIMEOUT = int(os.getenv("ARTICLE_FETCH_TIMEOUT", 30))
MAX_ARTICLE_LENGTH = int(os.getenv("MAX_ARTICLE_LENGTH", 5000))

frontend_path = os.path.join(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
    "frontend",
    "dist"
)

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


def update_constants_from_db(settings_dict):
    """
    Update global constants with values from the database settings.
    Environment variables take precedence over database settings.

    Args:
        settings_dict: Dictionary of settings from the database
    """
    global OLLAMA_HOST, MIN_CRON_HOURS, CRON_HOURS, SYNC_COOLDOWN_MINUTES
    global LLM_MODEL, LLM_TIMEOUT_SECONDS, OLLAMA_API_TIMEOUT_SECONDS
    global ARTICLE_FETCH_TIMEOUT, MAX_ARTICLE_LENGTH

    if 'ollama_host' in settings_dict and os.getenv("OLLAMA_HOST") is None:
        OLLAMA_HOST = settings_dict['ollama_host']

    if 'min_cron_hours' in settings_dict and os.getenv(
            "MIN_CRON_HOURS") is None:
        try:
            MIN_CRON_HOURS = float(settings_dict['min_cron_hours'])
        except (ValueError, TypeError):
            logger.warning(
                f"⚠️ Invalid min_cron_hours value in DB: "
                f"{settings_dict['min_cron_hours']}"
            )

    if 'cron_hours' in settings_dict and os.getenv("CRON_HOURS") is None:
        try:
            cron_hours_value = float(settings_dict['cron_hours'])
            CRON_HOURS = max(MIN_CRON_HOURS, cron_hours_value)
        except (ValueError, TypeError):
            logger.warning(
                f"⚠️ Invalid cron_hours value in DB: "
                f"{settings_dict['cron_hours']}"
            )

    if 'sync_cooldown_minutes' in settings_dict and os.getenv(
            "SYNC_COOLDOWN_MINUTES") is None:
        try:
            SYNC_COOLDOWN_MINUTES = int(settings_dict['sync_cooldown_minutes'])
        except (ValueError, TypeError):
            logger.warning(
                f"⚠️ Invalid sync_cooldown_minutes value in DB: "
                f"{settings_dict['sync_cooldown_minutes']}"
            )

    if 'llm_model' in settings_dict and os.getenv("LLM_MODEL") is None:
        LLM_MODEL = settings_dict['llm_model']

    if 'llm_timeout_seconds' in settings_dict and os.getenv(
            "LLM_TIMEOUT_SECONDS") is None:
        try:
            LLM_TIMEOUT_SECONDS = int(settings_dict['llm_timeout_seconds'])
        except (ValueError, TypeError):
            logger.warning(
                f"⚠️ Invalid llm_timeout_seconds value in DB: "
                f"{settings_dict['llm_timeout_seconds']}"
            )

    if 'ollama_api_timeout_seconds' in settings_dict and os.getenv(
            "OLLAMA_API_TIMEOUT_SECONDS") is None:
        try:
            OLLAMA_API_TIMEOUT_SECONDS = int(
                settings_dict['ollama_api_timeout_seconds'])
        except (ValueError, TypeError):
            logger.warning(
                f"⚠️ Invalid ollama_api_timeout_seconds value in DB: "
                f"{settings_dict['ollama_api_timeout_seconds']}"
            )

    if 'article_fetch_timeout' in settings_dict and os.getenv(
            "ARTICLE_FETCH_TIMEOUT") is None:
        try:
            ARTICLE_FETCH_TIMEOUT = int(settings_dict['article_fetch_timeout'])
        except (ValueError, TypeError):
            logger.warning(
                f"⚠️ Invalid article_fetch_timeout value in DB: "
                f"{settings_dict['article_fetch_timeout']}"
            )

    if 'max_article_length' in settings_dict and os.getenv(
            "MAX_ARTICLE_LENGTH") is None:
        try:
            MAX_ARTICLE_LENGTH = int(settings_dict['max_article_length'])
        except (ValueError, TypeError):
            logger.warning(
                f"⚠️ Invalid max_article_length value in DB: "
                f"{settings_dict['max_article_length']}"
            )
