"""
Parse akshare documentation files to extract function → data source mappings.

Scans all .md files under akshare/docs/data/ for the pattern:
    接口: <function_name>
    目标地址: <url>
    描述: <description>

Provides a lookup function to retrieve the source URL and description
for any given akshare function name.
"""

import os
import re
from functools import lru_cache
from typing import Dict, Optional, Tuple

# Pattern: lines like "接口: stock_sse_summary"
_INTERFACE_RE = re.compile(r"^接口:\s+(\S+)")
_URL_RE = re.compile(r"^目标地址:\s+(\S+)")
_DESC_RE = re.compile(r"^描述:\s+(.+)")


def _find_docs_dir() -> Optional[str]:
    """Locate the akshare docs/data directory relative to this project."""
    # Walk up from this file to find the akshare docs
    base = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    # Try sibling: ../akshare/docs/data/
    candidate = os.path.join(os.path.dirname(base), "akshare", "docs", "data")
    if os.path.isdir(candidate):
        return candidate
    return None


def _parse_doc_file(filepath: str) -> Dict[str, Tuple[str, str]]:
    """Parse a single .md doc file, returning {func_name: (url, description)}."""
    result = {}
    with open(filepath, "r", encoding="utf-8") as f:
        lines = f.readlines()

    i = 0
    while i < len(lines):
        m = _INTERFACE_RE.match(lines[i])
        if m:
            func_name = m.group(1)
            url = ""
            desc = ""
            # Look ahead for 目标地址 and 描述 (within next 6 lines)
            for j in range(i + 1, min(i + 7, len(lines))):
                um = _URL_RE.match(lines[j])
                if um:
                    url = um.group(1)
                dm = _DESC_RE.match(lines[j])
                if dm:
                    desc = dm.group(1)
            if url:
                result[func_name] = (url, desc)
        i += 1
    return result


@lru_cache(maxsize=1)
def _build_source_map() -> Dict[str, Tuple[str, str]]:
    """Build the complete function → (url, description) mapping from all doc files."""
    docs_dir = _find_docs_dir()
    if not docs_dir:
        return {}

    source_map: Dict[str, Tuple[str, str]] = {}
    for root, _dirs, files in os.walk(docs_dir):
        for fname in files:
            if fname.endswith(".md"):
                filepath = os.path.join(root, fname)
                source_map.update(_parse_doc_file(filepath))
    return source_map


def get_function_source(func_name: str) -> Optional[Tuple[str, str]]:
    """Get the data source info for a function.

    Returns (url, description) or None if not found.
    """
    return _build_source_map().get(func_name)
