#!/usr/bin/env python3
import argparse
import json
import os
import re
from pathlib import Path

CANDIDATE_NAMES = {
    "CLAUDE.md",
    "claude.md",
    "MEMORY.md",
    "memory.md",
    "AGENTS.md",
    "agents.md",
    "README.md",
    "readme.md",
    "qmd.yml",
    "qmd.yaml",
    "mempalace.json",
    ".mcp.json",
}

MODEL_PATTERNS = [
    ("mempalace", re.compile(r"all-MiniLM-L6-v2|MiniLM|384\b|ONNX|chroma", re.I)),
    ("qmd", re.compile(r"embeddinggemma-300M|embeddinggemma|1536\b|GGUF|BM25|rerank|collection add|qmd embed", re.I)),
]

EMBED_REGEXES = {
    "model_names": re.compile(r"(all-MiniLM-L6-v2|embeddinggemma-300M|embeddinggemma|MiniLM)", re.I),
    "dimensions": re.compile(r"\b(384|1536)\b"),
    "formats": re.compile(r"\b(ONNX|GGUF)\b", re.I),
    "context_window": re.compile(r"\b(256|8192)\b\s*(tokens?)?", re.I),
}

TEXT_EXTENSIONS = {
    ".md", ".txt", ".json", ".yml", ".yaml", ".toml", ".ini", ".cfg"
}


def is_text_candidate(path: Path) -> bool:
    if path.name in CANDIDATE_NAMES:
        return True
    return path.suffix.lower() in TEXT_EXTENSIONS and any(k in str(path).lower() for k in ["qmd", "mempalace", "memory", "claude", "agent", "embed"])


def scan_file(path: Path):
    try:
        text = path.read_text(encoding="utf-8", errors="ignore")
    except Exception:
        return None

    lower_text = text.lower()
    tool_hits = []
    evidence = []

    for tool, pattern in MODEL_PATTERNS:
        if pattern.search(text):
            tool_hits.append(tool)

    for label, regex in EMBED_REGEXES.items():
        for match in regex.finditer(text):
            start = max(0, match.start() - 80)
            end = min(len(text), match.end() + 120)
            snippet = text[start:end].replace("\n", " ").strip()
            evidence.append({
                "type": label,
                "match": match.group(0),
                "snippet": snippet,
            })

    if not tool_hits and not evidence and not any(k in lower_text for k in ["mempalace", "qmd", "embedding", "vector", "rerank", "memory"]):
        return None

    confidence = "low"
    if evidence and tool_hits:
        confidence = "high"
    elif evidence or tool_hits:
        confidence = "medium"

    return {
        "path": str(path),
        "tool_hits": sorted(set(tool_hits)),
        "confidence": confidence,
        "evidence": evidence[:12],
    }


def summarize(results):
    counts = {"mempalace": 0, "qmd": 0}
    model_mentions = set()
    for item in results:
        for tool in item["tool_hits"]:
            counts[tool] = counts.get(tool, 0) + 1
        for ev in item["evidence"]:
            if ev["type"] == "model_names":
                model_mentions.add(ev["match"])

    recommendation = "combined"
    if counts["qmd"] and not counts["mempalace"]:
        recommendation = "qmd"
    elif counts["mempalace"] and not counts["qmd"]:
        recommendation = "mempalace"

    return {
        "recommendation": recommendation,
        "counts": counts,
        "model_mentions": sorted(model_mentions),
    }


def main():
    parser = argparse.ArgumentParser(description="Inspect coding-agent memory/config files for embedding metadata and routing hints.")
    parser.add_argument("root", nargs="?", default=".", help="Repository or workspace root to scan")
    parser.add_argument("--max-files", type=int, default=250)
    args = parser.parse_args()

    root = Path(args.root).expanduser().resolve()
    candidates = []
    for path in root.rglob("*"):
        if len(candidates) >= args.max_files:
            break
        if path.is_file() and is_text_candidate(path):
            candidates.append(path)

    results = []
    for path in candidates:
        scanned = scan_file(path)
        if scanned:
            results.append(scanned)

    output = {
        "root": str(root),
        "summary": summarize(results),
        "files_checked": len(candidates),
        "matches": results,
    }
    print(json.dumps(output, indent=2))


if __name__ == "__main__":
    main()
