# Copyright (c) ZhangYundi
# Licensed under the MIT License

from pathlib import Path
from typing import List, Dict, Any

__all__ = ["get_docs_path", "get_knowledge_path", "search_knowledge"]

def _get_data_path() -> Path:
    """Get the data directory containing docs and knowledge"""
    try:
        import lidb
        pkg_path = Path(lidb.__file__).parent
        return pkg_path
    except Exception:
        import inspect
        return Path(inspect.getfile(inspect.currentframe())).parent.parent

def get_docs_path() -> Path:
    """Get the docs directory path - returns empty path if not available"""
    try:
        data_path = _get_data_path()
        if (data_path / "docs").exists():
            return data_path / "docs"
        if (data_path.parent / "docs").exists():
            return data_path.parent / "docs"
    except Exception:
        pass
    return Path("")

def get_knowledge_path() -> Path:
    """Get the knowledge directory path - returns empty path if not available"""
    try:
        data_path = _get_data_path()
        if (data_path / "knowledge").exists():
            return data_path.parent / "knowledge"
        if (data_path.parent / "knowledge").exists():
            return data_path.parent / "knowledge"
    except Exception:
        pass
    return Path("")

def search_knowledge(query: str, k: int = 5) -> List[Dict[str, Any]]:
    """Search knowledge base content - returns empty if not available"""
    docs_path = get_docs_path()
    knowledge_path = get_knowledge_path()

    results = []

    if docs_path and docs_path.exists():
        for doc_file in docs_path.glob("*.md"):
            try:
                with open(doc_file, "r", encoding="utf-8") as f:
                    content = f.read()
                lines = content.split("\n")
                for i, line in enumerate(lines):
                    if query.lower() in line.lower():
                        context = "\n".join(lines[max(0, i-2):i+3])
                        results.append({
                            "source": str(doc_file.relative_to(docs_path)),
                            "content": context,
                            "section": line.strip(),
                            "score": 1.0
                        })
            except Exception:
                continue

    if knowledge_path and knowledge_path.exists():
        for doc_file in knowledge_path.glob("docs/*.md"):
            try:
                with open(doc_file, "r", encoding="utf-8") as f:
                    content = f.read()
                lines = content.split("\n")
                for i, line in enumerate(lines):
                    if query.lower() in line.lower():
                        context = "\n".join(lines[max(0, i-2):i+3])
                        results.append({
                            "source": str(doc_file.relative_to(knowledge_path)),
                            "content": context,
                            "section": line.strip(),
                            "score": 1.0
                        })
            except Exception:
                continue

    return sorted(results, key=lambda x: x["score"], reverse=True)[:k]
