import os
import re
import sys

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")
if hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8")

root_dir = r"c:\Projects\FreeExile"

def check_links_in_dir(scan_dir):
    broken_links = []
    rel_links = []
    file_links = []
    total_links = 0
    file_count = 0

    for root, dirs, files in os.walk(scan_dir):
        for f in files:
            if f.endswith(".md"):
                file_count += 1
                p = os.path.join(root, f)
                rel_file = os.path.relpath(p, root_dir)
                with open(p, "r", encoding="utf-8", errors="ignore") as fp:
                    content = fp.read()
                
                # match markdown links [text](target)
                matches = re.findall(r'\[([^\]]+)\]\(([^)]+)\)', content)
                for text, target in matches:
                    total_links += 1
                    target_clean = target.split("#")[0].strip()
                    if not target_clean:
                        continue # just anchor
                    
                    if target.startswith("file:///"):
                        file_links.append((rel_file, target))
                        norm = target_clean.replace("file:///", "").replace("/", os.sep)
                        if not os.path.exists(norm):
                            broken_links.append((rel_file, target, "FILE_NOT_FOUND"))
                    elif target.startswith("http://") or target.startswith("https://"):
                        pass
                    else:
                        rel_links.append((rel_file, target))
                        # Resolve relative to current file's directory
                        resolved = os.path.normpath(os.path.join(root, target_clean))
                        if not os.path.exists(resolved):
                            broken_links.append((rel_file, target, "REL_FILE_NOT_FOUND"))
                            
    return file_count, total_links, len(file_links), len(rel_links), broken_links

print("=== CHECKING WIKI LINKS ===")
fc, tl, fl, rl, bl = check_links_in_dir(r"c:\Projects\FreeExile\wiki")
print(f"Wiki: {fc} files, {tl} links ({fl} file:///, {rl} relative). Broken: {len(bl)}")
for f, l, err in bl:
    print(f"  [X] {f}: {l} -> {err}")

print("\n=== CHECKING DOCS LINKS ===")
fc_d, tl_d, fl_d, rl_d, bl_d = check_links_in_dir(r"c:\Projects\FreeExile\docs")
print(f"Docs: {fc_d} files, {tl_d} links ({fl_d} file:///, {rl_d} relative). Broken: {len(bl_d)}")
for f, l, err in bl_d:
    print(f"  [X] {f}: {l} -> {err}")
