# -*- coding: utf-8 -*-
# Map hardcoded CSS colours in every default control to var(--ui-token, <orig>) so themes can
# recolour everything. Fallback = original colour -> current look preserved until a theme overrides.
import json, glob, re, os, sys
sys.stdout.reconfigure(encoding='utf-8')
ROOT = r"e:/files/iobroker my adapters/iobroker.webui my edited/iobroker.webui/default-controls/controls"

# color(lower) -> token
M = {}
def add(tok, *cols):
    for c in cols: M[c.lower()] = tok
add('--ui-ok', '#10b981','#2e7d32','#1b5e20','#00ff00','#37d67a','#2be08f','#00b894','#55efc4','#4caf50','#43a047','#66bb6a','#2ecc71','#27ae60','#99ff33')
add('--ui-error', '#ef4444','#ff0000','#d63b45','#e8384f','#e01e5a','#d63031','#f44336','#e74c3c','#c0392b','#ef4d5e','#ff7675','#b71c1c','#e91e63')
add('--ui-warn', '#fbbf24','#ffff00','#f6b73c','#e64a19','#bf360c','#f5a623','#ff9800','#ffa726','#fb8c00','#c8551f','#e67e22','#f39c12','#ffa500')
add('--accent', '#2196f3','#2962ff','#1976d2','#2680eb','#2b8bff','#0078d4','#1e88e5','#42a5f5','#2f7bff','#0984e3','#74b9ff','#2196f3')
add('--ui-text', '#e2e6ec','#e8e8ea','#e8eaf0','#f2f4f8','#eaf2ff','#e0e0e0','#dfe6e9')
add('--ui-dim', '#9aa3b0','#a8c8e8','#7ab4d8','#636e72','#95a5a6','#b2bec3')
add('--ui-surface', '#252b38','#232733','#272733','#2a2f3a','#1a2030','#2a3442','#1f2937','#141720','#232b3a','#1e293b','#2d3436','#1a1f3a','#0a0e27')
add('--ui-surface-2', '#2f3545','#3b3a4e','#383f52','#2d3748','#374151')
add('--ui-input', '#3a3f4b','#383f52')
add('--ui-border', '#4a5570','#3b4250','#596c7a','#d4dae3','#ccc','#ddd','#4a6a6a','#3a5a5a','#b2bec3','#d0d0d0')

# controls whose colours are their OWN theme system or already tokenised -> skip
SKIP = ('navigation/', 'gauges/', 'theme/')

files = glob.glob(os.path.join(ROOT, "**", "*.control"), recursive=True)
total_files, total_reps = 0, 0
# match #rrggbb or #rgb as whole tokens (not inside var())
hexre = re.compile(r'(?<![\w)])#[0-9a-fA-F]{6}\b|(?<![\w)])#[0-9a-fA-F]{3}\b')
for fp in files:
    rel = os.path.relpath(fp, ROOT).replace('\\','/')
    if any(rel.startswith(s) for s in SKIP): continue
    d = json.load(open(fp, encoding='utf-8'))
    style = d.get('style') or ''
    if not style: continue
    reps = [0]
    def sub(m):
        c = m.group(0).lower()
        tok = M.get(c)
        if not tok: return m.group(0)
        reps[0]+=1
        return f'var({tok},{m.group(0)})'
    new = hexre.sub(sub, style)
    if reps[0]:
        d['style'] = new
        json.dump(d, open(fp,'w',encoding='utf-8'), ensure_ascii=False)
        total_files += 1; total_reps += reps[0]
        print(f'{reps[0]:3d}  {rel}')
print('---')
print('files changed:', total_files, ' total color->token:', total_reps)
