# =============================================================
# telegram_bot/knowledge_loader.py — Knowledge Base Ielādētājs
# =============================================================
# Nolasa .md failus no knowledge_base/ mapītē.
# Bots izmanto šo saturu kā atbilžu bāzi.
# =============================================================

from pathlib import Path

# Ceļš uz knowledge_base mapi (blakus šim failam)
KNOWLEDGE_BASE_DIR = Path(__file__).resolve().parent / "knowledge_base"

# Tēmu definīcijas — inline pogu teksti un failu nosaukumi
QUICK_TOPICS = {
    "par_ai": {
        "title": "🤖 Kas ir AI?",
        "file": "par_ai",
    },
    "par_mums": {
        "title": "🚀 MIM.LV",
        "file": "par_mums",
    },
    "asistents": {
        "title": "🧠 Personīgais AI Asistents",
        "file": "par_mums",
    },
    "faq": {
        "title": "❓ Biežākie jautājumi",
        "file": "faq",
    },
}

# Atslēgvārdi → tēmas (brīvā teksta apstrādei)
KEYWORD_MAP = {
    "par_ai": [
        "ai", "mākslīg", "inteliģenc", "llm", "gpt", "claude",
        "modelis", "neironu", "machine learning", "automatizācij",
    ],
    "asistents": [
        "asistent", "čatbot", "bot", "palīgs", "personīg",
        "izveidot", "vēlos", "gribu", "cena", "maksā",
    ],
    "par_mums": [
        "mim", "mim.lv", "uzņēmum", "jūsu", "par jums",
        "pakalpojum", "web", "izstrād", "menedžeris"
    ],
    "faq": [
        "jautājum", "kā", "cik ilgi", "vai", "konfidenciāl",
        "drošīb", "bezmaksas", "latviešu",
    ],
}


def load_knowledge_base() -> dict:
    """Nolasa visus .md failus no knowledge_base/ mapes."""
    knowledge = {}

    if not KNOWLEDGE_BASE_DIR.exists():
        return knowledge

    for md_file in KNOWLEDGE_BASE_DIR.glob("*.md"):
        try:
            knowledge[md_file.stem] = md_file.read_text(encoding="utf-8")
        except Exception:
            pass

    return knowledge


def get_topic_text(topic_key: str) -> str:
    """Atgriež konkrētas tēmas tekstu, formatētu Telegram Markdown stilā."""
    knowledge = load_knowledge_base()
    topic_info = QUICK_TOPICS.get(topic_key)

    if not topic_info:
        return "❌ Tēma nav atrasta."

    raw = knowledge.get(topic_info["file"], "Saturs nav pieejams.")
    formatted = _md_to_telegram(raw)

    # Telegram max ziņas garums = 4096 rakstzīmes
    if len(formatted) > 4000:
        formatted = formatted[:4000] + "\n\n_[Skatīt vairāk: mim.lv]_"

    return formatted


def detect_topic(user_text: str) -> str | None:
    """Meklē atslēgvārdus lietotāja tekstā un atgriež piemērotāko tēmu."""
    best_topic = None
    best_score = 0

    for topic, keywords in KEYWORD_MAP.items():
        score = sum(1 for kw in keywords if kw in user_text)
        if score > best_score:
            best_score = score
            best_topic = topic

    return best_topic if best_score > 0 else None


def _md_to_telegram(text: str) -> str:
    """Vienkārša Markdown → Telegram MarkdownV1 konversija."""
    lines = []
    for line in text.split("\n"):
        if line.startswith("# "):
            line = f"✦ *{line[2:].strip()}*"
        elif line.startswith("## "):
            line = f"\n*{line[3:].strip()}*"
        elif line.startswith("### "):
            line = f"_{line[4:].strip()}_"
        # **bold** → *bold*
        line = line.replace("**", "*")
        lines.append(line)
    return "\n".join(lines)