#!/usr/bin/env python3
"""Remplace les anciennes valeurs d'etat par les nouvelles (iTop) dans tous les fichiers Python et templates."""
import os
import re

# Ordre important: plus specifiques d'abord
REPLACEMENTS = [
    ("en_decommissionnement", "obsolete"),
    ("en_implementation", "implementation"),
    ("en_production", "production"),
    ("decommissionne", "obsolete"),
    ("en_cours", "implementation"),  # prudent: seulement si etat context
    ("'eteint'", "'obsolete'"),
    ('"eteint"', '"obsolete"'),
    ("'eol'", "'obsolete'"),
    ('"eol"', '"obsolete"'),
]

# Ne PAS toucher:
# - itop_service.py (mappings deja corrects, on les laisse pour rétro-compat)
# - migrate_etat.sql (script de migration)
# - les tests
SKIP_FILES = {
    "itop_service.py",  # contient le mapping historique
}

ROOT = "app"
count = 0
for root, dirs, files in os.walk(ROOT):
    for f in files:
        if not f.endswith((".py", ".html")):
            continue
        if f in SKIP_FILES:
            continue
        path = os.path.join(root, f)
        with open(path, encoding="utf-8") as fh:
            content = fh.read()
        orig = content
        for old, new in REPLACEMENTS:
            # en_cours est ambigu : on ne remplace que dans contexte etat
            if old == "en_cours":
                content = re.sub(r"(etat\s*[=:]\s*['\"])en_cours(['\"])", r"\1implementation\2", content)
                content = re.sub(r"\betat\s*==\s*['\"]en_cours['\"]", "etat == 'implementation'", content)
                continue
            content = content.replace(old, new)
        if content != orig:
            with open(path, "w", encoding="utf-8") as fh:
                fh.write(content)
            print(f"  modified: {path}")
            count += 1

print(f"\nTotal: {count} files modified")
