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

def version_parse(v):
    return tuple(map(int, (v.split("."))))

# Configuration
EN_FOLDER = "ISO27002-EN-2022"
EN_PATTERN = re.compile(r'ISO_27002_2022_([\d\.]+)_OT(.*)\.md')

# Match (see n.n[, n.n]* [and n.n]*) references including missing space cases
REF_REPLACE_PATTERN = re.compile(r'\(see ([\d\.\,\sand]+)\)')

def main():
    # Build index of EN files by section number
    en_index = {}
    for filename in os.listdir(EN_FOLDER):
        if not filename.endswith('.md'):
            continue
        match = EN_PATTERN.match(filename)
        if match:
            section = match.group(1)
            en_index[section] = filename
    
    print(f"Indexed {len(en_index)} EN files")
    print()
    
    processed = 0
    total_replacements = 0
    
    for filename in os.listdir(EN_FOLDER):
        if not filename.endswith('.md'):
            continue
        file_path = os.path.join(EN_FOLDER, filename)
        
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        replacements = 0
        
        def replace_reference(match):
            nonlocal replacements
            references_str = match.group(1)
            # Normalize: handle "and", "and", and missing space "5.16and5.18"
            references_str = re.sub(r'(\d)and', r'\1 and', references_str)
            references_str = references_str.replace(" and ", ", ")
            refs = [r.strip() for r in references_str.split(',') if r.strip()]
            processed_refs = []
            
            for ref in refs:
                if ref in en_index:
                    target_file = en_index[ref].replace(' ', '%20')
                    processed_refs.append(f'[{ref}]({target_file})')
                    replacements += 1
                else:
                    processed_refs.append(ref)
            
            return f'(see {", ".join(processed_refs)})'
        
        updated_content = REF_REPLACE_PATTERN.sub(replace_reference, content)
        
        if replacements > 0:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(updated_content)
            processed += 1
            total_replacements += replacements
            print(f"✅ {filename}: {replacements} links created")
    
    print()
    print(f"Completed: {processed} files modified")
    print(f"Total markdown links created: {total_replacements}")

if __name__ == "__main__":
    main()
