import json
import subprocess

def run_cargo_check():
    cmd = ["cargo", "check", "-p", "entropyk-components", "--message-format=json"]
    result = subprocess.run(cmd, capture_output=True, text=True)
    return result.stdout.splitlines()

def patch_file(filepath, lines_to_patch):
    # lines_to_patch is a list of 1-based line numbers
    with open(filepath, 'r') as f:
        lines = f.readlines()
        
    lines_to_patch = sorted(list(set(lines_to_patch)), reverse=True)
    for line_num in lines_to_patch:
        idx = line_num - 1
        if idx < 0 or idx >= len(lines): continue
        
        # calculate indent
        line_content = lines[idx]
        indent = line_content[:len(line_content) - len(line_content.lstrip())]
        
        # check if it already has a doc string
        if idx > 0 and lines[idx-1].strip().startswith("///"):
            continue
            
        lines.insert(idx, f"{indent}/// Documentation pending\n")
        
    with open(filepath, 'w') as f:
        f.writelines(lines)

def main():
    lines = run_cargo_check()
    patches = {}
    
    for line in lines:
        try:
            msg = json.loads(line)
            if msg.get("reason") == "compiler-message":
                compiler_msg = msg["message"]
                if compiler_msg["code"] and compiler_msg["code"]["code"] == "missing_docs":
                    spans = compiler_msg["spans"]
                    for span in spans:
                        if span["is_primary"]:
                            filename = span["file_name"]
                            line_num = span["line_start"]
                            if filename not in patches:
                                patches[filename] = []
                            patches[filename].append(line_num)
        except Exception as e:
            pass
            
    for filename, lines_to_patch in patches.items():
        print(f"Patching {filename} - {len(lines_to_patch)} locations")
        patch_file(filename, lines_to_patch)

if __name__ == "__main__":
    for _ in range(3): # run multiple passes as some docs might shift line numbers
        main()
        
