const fs = require('fs');
const path = require('path');

const styleDir = path.join(__dirname, '../common/style/memberInfo');

/** 硬编码 px → 统一字号变量（从大到小替换，避免误匹配） */
const fontSizePxMap = [
    ['32px', 'var(--font-size-5xl)'],
    ['28px', 'var(--font-size-4xl)'],
    ['24px', 'var(--font-size-3xl)'],
    ['22px', 'var(--font-size-2xl)'],
    ['20px', 'var(--font-size-xl)'],
    ['18px', 'var(--font-size-lg)'],
    ['17px', 'var(--font-size-md)'],
    ['16px', 'var(--font-size-md)'],
    ['15px', 'var(--font-size-base)'],
    ['14px', 'var(--font-size-base)'],
    ['13px', 'var(--font-size-base)'],
    ['12px', 'var(--font-size-sm)'],
    ['11px', 'var(--font-size-xs)'],
    ['10px', 'var(--font-size-xs)']
];

function walk(dir) {
    for (const name of fs.readdirSync(dir)) {
        const full = path.join(dir, name);
        if (fs.statSync(full).isDirectory()) {
            walk(full);
            continue;
        }
        if (!name.endsWith('.css')) continue;
        normalize(full);
    }
}

function normalize(filePath) {
    let css = fs.readFileSync(filePath, 'utf8');
    let next = css;

    const fontFamilyMap = [
        ['"Noto Sans SC-Bold"', 'var(--font-family)'],
        ['"Noto Sans SC-Medium"', 'var(--font-family)'],
        ['"Noto Sans SC-Regular"', 'var(--font-family)'],
        ['"Noto Sans SC-SemiBold"', 'var(--font-family)'],
        ['"Inter-Semi Bold"', 'var(--font-family)'],
        ['"Inter-Bold"', 'var(--font-family)'],
        ['"Inter-Regular"', 'var(--font-family)']
    ];
    for (const [from, to] of fontFamilyMap) {
        next = next.split(`font-family: ${from}`).join(`font-family: ${to}`);
    }

    const weightMap = [
        ['font-weight: Bold', 'font-weight: 700'],
        ['font-weight: Medium', 'font-weight: 500'],
        ['font-weight: Regular', 'font-weight: 400'],
        ['font-weight: SemiBold', 'font-weight: 600'],
        ['font-weight: Semi Bold', 'font-weight: 600']
    ];
    for (const [from, to] of weightMap) {
        next = next.split(from).join(to);
    }

    next = next.replace(/white-space:\s*pre;/g, 'white-space: nowrap;');

    for (const [px, token] of fontSizePxMap) {
        next = next.replace(new RegExp(`font-size:\\s*${px.replace('.', '\\.')};`, 'g'), `font-size: ${token};`);
    }

    if (next !== css) {
        fs.writeFileSync(filePath, next, 'utf8');
        console.log('normalized', path.relative(styleDir, filePath));
    }
}

walk(styleDir);
console.log('done');
