import os
import re

wiki_dir = r"c:\Projects\FreeExile\wiki"
docs_dir = r"c:\Projects\FreeExile\docs"

def audit_file(rel, p):
    with open(p, "r", encoding="utf-8", errors="ignore") as fp:
        lines = fp.readlines()
    content = "".join(lines)
    
    tables = [l for l in lines if "|" in l]
    headers = [l.strip() for l in lines if l.startswith("#")]
    prompts = [l.strip() for l in lines if "Prompt" in l or "Concept Art" in l]
    code_blocks = [l for l in lines if l.strip().startswith("```")]
    links = re.findall(r"\[([^\]]+)\]\(([^)]+)\)", content)
    file_links = [l for l in links if l[1].startswith("file:///")]
    rel_links = [l for l in links if not l[1].startswith("file:///") and not l[1].startswith("http")]
    http_links = [l for l in links if l[1].startswith("http")]

    # Check for lore/storytelling markers
    lore_patterns = [
        "Sau biến cố", "thập tử nhất sinh", "máu, xương", "tiên nhân", "tiên cảnh",
        "phi thăng", "oán khí", "rỉ máu", "tàn khốc", "khát máu", "tàn sát",
        "Visual Concept Art Prompt", "Concept Art Prompt"
    ]
    lore_hits = sum(1 for pat in lore_patterns if pat.lower() in content.lower())

    return {
        "rel": rel,
        "lines": len(lines),
        "size": os.path.getsize(p),
        "table_lines": len(tables),
        "headers_count": len(headers),
        "prompts_count": len(prompts),
        "code_block_markers": len(code_blocks),
        "total_links": len(links),
        "file_links": len(file_links),
        "rel_links": len(rel_links),
        "http_links": len(http_links),
        "lore_hits": lore_hits,
        "h1": headers[0] if headers else ""
    }

print("=== WIKI AUDIT ===")
wiki_results = []
for root, dirs, files in os.walk(wiki_dir):
    for f in sorted(files):
        if f.endswith(".md"):
            p = os.path.join(root, f)
            rel = os.path.relpath(p, r"c:\Projects\FreeExile")
            wiki_results.append(audit_file(rel, p))

for d in sorted(wiki_results, key=lambda x: x["rel"]):
    print(f"{d['rel']:<50} | {d['lines']:>3}L | {d['size']:>5}B | tbl:{d['table_lines']:>2} | h:{d['headers_count']:>2} | lore:{d['lore_hits']:>2} | lnk:{d['total_links']:>2} (file:{d['file_links']}, rel:{d['rel_links']})")

print("\n=== DOCS AUDIT (TOP 25 BY LENGTH) ===")
docs_results = []
for root, dirs, files in os.walk(docs_dir):
    for f in sorted(files):
        if f.endswith(".md"):
            p = os.path.join(root, f)
            rel = os.path.relpath(p, r"c:\Projects\FreeExile")
            docs_results.append(audit_file(rel, p))

for d in sorted(docs_results, key=lambda x: -x["lines"])[:25]:
    status = "OK"
    if d["lines"] > 600:
        status = "HARD_CAP_VIOLATION"
    elif d["lines"] > 400:
        status = "SOFT_CAP_WARNING"
    print(f"[{status:<17}] {d['rel']:<65} | {d['lines']:>3}L | {d['size']:>5}B | tbl:{d['table_lines']:>2} | lnk:{d['total_links']:>2} (file:{d['file_links']}, rel:{d['rel_links']})")
