import os
import re

# Comprehensive Mapping
MAPPING = [
    # Git / URLs
    ('https://github.com/paritytech/polkadot-sdk', 'https://github.com/pezkuwichain/pezkuwi-sdk'),
    ('https://github.com/polkadotchain/polkadot-sdk', 'https://github.com/pezkuwichain/pezkuwi-sdk'),
    ('paritytech', 'pezkuwichain'),
    ('polkadotchain', 'pezkuwichain'),
    
    # Core Brands
    ('Polkadot SDK', 'Pezkuwi SDK'),
    ('polkadot-sdk', 'pezkuwi-sdk'),
    ('Polkadot', 'Pezkuwi'),
    ('polkadot', 'pezkuwi'),
    ('Substrate', 'Bizinikiwi'),
    ('substrate', 'bizinikiwi'),
    ('Cumulus', 'Pezcumulus'),
    ('cumulus', 'pezcumulus'),
    ('Parachain', 'Teyrchain'),
    ('parachain', 'teyrchain'),
    
    # Networks
    ('Rococo', 'Pezkuwichain'),
    ('rococo', 'pezkuwichain'),
    ('Westend', 'Zagros'),
    ('westend', 'zagros'),
    
    # Tokens
    ('DOT', 'HEZ'),
    ('WND', 'ZGR'),
    ('ROC', 'TYR'),
    
    # Components (with prefix protection to avoid pezpez)
    (r'(?<!pez)frame', 'pezframe'),
    (r'(?<!pez)FRAME', 'PEZFRAME'),
    (r'(?<!pez)Frame', 'Pezframe'),
    (r'(?<!pez)pallet', 'pezpallet'),
    (r'(?<!pez)PALLET', 'PEZPALLET'),
    (r'(?<!pez)Pallet', 'Pezpallet'),
    
    # Prefixes (very dangerous, must be careful)
    # sc- -> pezsc-
    # sp- -> pezsp-
    (r'(?<!pez)sc-', 'pezsc-'),
    (r'(?<!pez)sp-', 'pezsp-'),
    (r'(?<!pez)sc_', 'pezsc_'),
    (r'(?<!pez)sp_', 'pezsp_'),
]

# REBRAND_MAP from docs/REBRAND_PROGRESS.md (abbreviated or synthesized)
# We apply these AFTER the general rules if they are not covered.
# Actually, the general rules cover most sc/sp/pallet/frame cases.

EXTENSIONS = ('.rs', '.toml', '.adoc', '.md', '.sh', '.yml', '.yaml', '.json')

def rebrand_content(content):
    for pattern, replacement in MAPPING:
        if pattern.startswith(r'(?<!pez)'):
            content = re.sub(pattern, replacement, content)
        else:
            content = content.replace(pattern, replacement)
    return content

def main():
    for root, dirs, files in os.walk('.'):
        if '.git' in dirs:
            dirs.remove('.git')
        if 'target' in dirs:
            dirs.remove('target')
            
        for file in files:
            if file.endswith(EXTENSIONS):
                path = os.path.join(root, file)
                try:
                    with open(path, 'r', encoding='utf-8') as f:
                        content = f.read()
                    
                    new_content = rebrand_content(content)
                    
                    if content != new_content:
                        with open(path, 'w', encoding='utf-8') as f:
                            f.write(new_content)
                        # print(f"Rebranded content: {path}")
                except Exception as e:
                    print(f"Error processing {path}: {e}")

if __name__ == "__main__":
    main()
