import os
import re
import sys
import subprocess
from glob import glob

# Assets
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.dirname(BASE_DIR)
MANAGE_REGISTRY_SCRIPT = os.path.join(BASE_DIR, "manage_registry.py")
CONVERT_PDF_SCRIPT = os.path.join(BASE_DIR, "convert_to_pdf.py")

def get_manual_level(filename):
    """Infer level from filename [Nível X] ..."""
    match = re.search(r'\[Nível\s*(\d+)\]', filename, re.IGNORECASE)
    if match:
        return int(match.group(1))
    
    # Fallback: check parent folder name
    if "Nivel_0" in filename: return 0
    if "Nivel_1" in filename: return 1
    if "Nivel_2" in filename: return 2
    if "Nivel_3" in filename: return 3
    
    return None

def update_manual(file_path):
    filename = os.path.basename(file_path)
    
    # Skip non-manuals
    if filename.lower() == "gemini.md" or "readme" in filename.lower() or "legado" in file_path.lower():
        print(f"Skipping: {filename}")
        return

    level = get_manual_level(file_path)
    if level is None:
        print(f"Skipping (Unknown Level): {filename}")
        return

    # Extract Title (everything after [Nível X])
    clean_title = re.sub(r'\[Nível\s*\d+\]', '', filename).replace('.md', '').strip(" -_")
    
    print(f"Processing: {filename} | Level: {level} | Title: {clean_title}")

    # 1. Generate New Code
    try:
        cmd = [sys.executable, MANAGE_REGISTRY_SCRIPT, "--level", str(level), "--title", clean_title]
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        
        # Extract code from stdout (looking for "SUCCESS: Generated Code: X")
        code_match = re.search(r'Generated Code:\s*(ITG[A-Z]+\s+\d{4}/\d{2})', result.stdout)
        if not code_match:
            print(f"Failed to generate code for {filename}. Output: {result.stdout}")
            return
        
        new_code = code_match.group(1)
        print(f"  -> New Code: {new_code}")
        
    except subprocess.CalledProcessError as e:
        print(f"Error calling registry script: {e}")
        return

    # 2. Update Markdown Content
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # Regex to find existing code line or insert it
    # Pattern looks for "**Código:** ITITG ... |" or similar
    code_pattern = re.compile(r'(\*\*Código:\*\*).*?(\|)')
    
    if code_pattern.search(content):
        # Update existing
        new_content = code_pattern.sub(f"**Código:** {new_code} |", content)
    else:
        # Insert after title (assuming standard format)
        # This is trickier, so for now we append simple replacement logic or just manual check
        # But given the request to "update", let's assume they might have old headers
        # Let's simple look for the "Código:" string
         new_content = re.sub(r'Código:.*?\|', f"Código: {new_code} |", content)

    if new_content != content:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(new_content)
        print("  -> Markdown updated.")
    else:
        print("  -> No header change needed (or header not found).")
        # Ensure we write at least once to touch the file? No.
        
        # Force Insert if standard header missing?
        # Let's try to be smart: if it's an old manual without header, we might need to prepend it
        # validating against the standard template.
        pass

    # 3. Regenerate PDF
    print("  -> Generating PDF...")
    try:
        subprocess.run([sys.executable, CONVERT_PDF_SCRIPT, file_path], check=True)
        print("  -> PDF Done.")
    except subprocess.CalledProcessError as e:
        print(f"  -> PDF Generation Failed: {e}")

def main():
    # Find all .md files in parent dir recursively
    search_path = os.path.join(PROJECT_ROOT, "**", "*.md")
    files = glob(search_path, recursive=True)
    
    for f in files:
        if ".gemini" in f: continue
        update_manual(f)

if __name__ == "__main__":
    main()
