"""
BizNode Local Bot Starter
==========================
Loads .env into os.environ and launches the Telegram bot locally
(outside Docker). Use this when Docker is unavailable.

Usage:
    python restart/start_bot.py
    python restart/start_bot.py > logs/bot_local.log 2>&1   (background)
"""

import os
import sys

PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(PROJECT_ROOT)
sys.path.insert(0, PROJECT_ROOT)

# ── Load .env ────────────────────────────────────────────────────────────────
env_file = os.path.join(PROJECT_ROOT, ".env")
if os.path.exists(env_file):
    with open(env_file, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            k, _, v = line.partition("=")
            k, v = k.strip(), v.strip().strip('"').strip("'")
            if k:
                os.environ[k] = v

# ── Set bot-specific env vars ────────────────────────────────────────────────
os.environ["BOT_TOKEN"] = os.environ.get("TELEGRAM_BOT_TOKEN", "")
os.environ["OLLAMA_URL"] = os.environ.get("OLLAMA_URL", "http://localhost:11434/api/generate")
os.environ["OLLAMA_EMBED_URL"] = os.environ.get("OLLAMA_EMBED_URL", "http://localhost:11434/api/embeddings")
os.environ["QDRANT_URL"] = os.environ.get("QDRANT_URL", "http://localhost:6333")
os.environ["OLLAMA_MODEL"] = os.environ.get("LLM_MODEL", "qwen3.5:4b")
os.environ["EMBEDDING_MODEL"] = os.environ.get("EMBEDDING_MODEL", "nomic-embed-text")
os.environ["DASHBOARD_URL"] = os.environ.get("DASHBOARD_URL", "http://localhost:7777")

# ── Create log directory (bot expects /app/logs inside Docker) ───────────────
os.makedirs(os.path.join(PROJECT_ROOT, "logs"), exist_ok=True)
os.makedirs("C:/app/logs", exist_ok=True)

# ── Launch bot ───────────────────────────────────────────────────────────────
bot_script = os.path.join(PROJECT_ROOT, "docker", "bot", "run_bot.py")
with open(bot_script, encoding="utf-8") as f:
    exec(f.read())
