#!/usr/bin/env python3
"""
Scan ele-admin-pro Less files for AntDv3 variable references,
then add missing variables to antd-less-stub/default.less
"""
import re
import os
import sys

# Paths
ELE_ADMIN_PATH = "/Users/gxwebsoft/VUE/paopao-vue/node_modules/.pnpm/ele-admin-pro@1.11.1_ant-design-vue@4.2.6_vue@3.5.3_typescript@5.9.3___vue@3.5.3_typescript@5.9.3_/node_modules/ele-admin-pro/es"
STUB_FILE = "/Users/gxwebsoft/VUE/paopao-vue/src/styles/antd-less-stub/default.less"

# Common AntDv3 variable default values
ANTDV3_DEFAULTS = {
    # Select
    'select-multiple-item-height': '24px',
    'select-multiple-item-spacing-half': '4px',
    'select-selection-item-bg': '#f5f5f5',
    'select-selection-item-border-color': '#d9d9d9',
    'select-selection-item-disabled-color': 'rgba(0, 0, 0, 0.25)',
    'select-selection-item-disabled-border-color': '#d9d9d9',
    'select-background': '#ffffff',
    'select-border-color': '#d9d9d9',
    'select-dropdown-bg': '#ffffff',
    'select-dropdown-height': '200px',
    'select-clear-width': '20px',
    'select-padding-horizontal': '12px',
    'select-font-size': '14px',
    # Input
    'input-padding-vertical-base': '4px',
    'input-padding-horizontal-base': '12px',
    'input-height-base': '32px',
    'input-placeholder-color': 'rgba(0, 0, 0, 0.25)',
    'input-color': 'rgba(0, 0, 0, 0.88)',
    'input-border-color': '#d9d9d9',
    'input-bg': '#ffffff',
    'input-disabled-bg': '#f5f5f5',
    'input-hover-border-color': '#1677ff',
    'input-focus-border-color': '#1677ff',
    # Form
    'form-item-margin-bottom': '24px',
    'form-vertical-label-padding': '0 0 8px',
    'form-vertical-label-margin': '0',
    'form-item-label-width': 'auto',
    'form-item-label-margin-right': '8px',
    # Button
    'btn-height-base': '32px',
    'btn-height-lg': '40px',
    'btn-height-sm': '24px',
    'btn-font-size-base': '14px',
    'btn-font-size-lg': '16px',
    'btn-font-size-sm': '12px',
    'btn-padding-horizontal-base': '15px',
    'btn-padding-horizontal-lg': '23px',
    'btn-padding-horizontal-sm': '7px',
    'btn-border-radius-base': '6px',
    'btn-primary-bg': '#1677ff',
    'btn-primary-color': '#fff',
    'btn-default-bg': '#ffffff',
    'btn-default-color': 'rgba(0, 0, 0, 0.88)',
    'btn-default-border-color': '#d9d9d9',
    # Menu
    'menu-item-height': '40px',
    'menu-inline-toplevel-item-height': '40px',
    'menu-collapsed-width': '80px',
    'menu-bg': '#ffffff',
    'menu-item-color': 'rgba(0, 0, 0, 0.65)',
    'menu-highlight-color': '#1677ff',
    'menu-item-active-bg': '#e6f4ff',
    # Table
    'table-header-bg': '#fafafa',
    'table-header-color': 'rgba(0, 0, 0, 0.88)',
    'table-row-hover-bg': '#fafafa',
    'table-border-color': '#f0f0f0',
    'table-header-cell-split-color': '#f0f0f0',
    'table-padding-vertical': '8px',
    'table-padding-horizontal': '8px',
    # Modal
    'modal-header-padding': '16px 24px',
    'modal-content-bg': '#ffffff',
    'modal-heading-color': 'rgba(0, 0, 0, 0.88)',
    'modal-close-color': 'rgba(0, 0, 0, 0.45)',
    'modal-mask-bg': 'rgba(0, 0, 0, 0.45)',
    # Layout
    'layout-header-height': '64px',
    'layout-sider-width': '200px',
    'layout-trigger-height': '48px',
    # Checkbox
    'checkbox-check-color': '#fff',
    # Radio
    'radio-dot-size': '8px',
    'radio-dot-color': '#1677ff',
    # Switch
    'switch-height': '22px',
    'switch-small-height': '16px',
    'switch-min-width': '44px',
    # Slider
    'slider-rail-height': '4px',
    'slider-handle-size': '14px',
    'slider-dot-border-color': '#d9d9d9',
    # DatePicker
    'datepicker-bg': '#ffffff',
    'datepicker-border-color': '#d9d9d9',
    # TimePicker
    'timepicker-bg': '#ffffff',
    'timepicker-border-color': '#d9d9d9',
    # Upload
    'upload-actions-color': 'rgba(0, 0, 0, 0.45)',
    # Progress
    'progress-remaining-color': 'rgba(0, 0, 0, 0.04)',
    # Spin
    'spin-dot-size': '20px',
    # Anchor
    'anchor-border-color': '#f0f0f0',
    # BackTop
    'backtop-bg': 'rgba(0, 0, 0, 0.45)',
    'backtop-color': '#fff',
    # Typography
    'typography-title-margin-top': '1.2em',
    'typography-title-margin-bottom': '0.5em',
}

def find_less_files(base_path):
    """Find all .less files in ele-admin-pro"""
    less_files = []
    for root, dirs, files in os.walk(base_path):
        for f in files:
            if f.endswith('.less'):
                less_files.append(os.path.join(root, f))
    return less_files

def extract_variable_references(less_files):
    """Extract all @variable references from Less files (not definitions)"""
    refs = set()
    # Pattern matches @var-name not followed by : (not a definition)
    # Also exclude @{var} interpolation syntax
    for fpath in less_files:
        try:
            with open(fpath, 'r', encoding='utf-8') as f:
                content = f.read()
                # Find all @var-name patterns
                matches = re.findall(r'@([a-zA-Z_][a-zA-Z0-9_-]*)', content)
                for m in matches:
                    refs.add(m)
        except Exception as e:
            print(f"Error reading {fpath}: {e}", file=sys.stderr)
    return refs

def get_defined_variables(stub_file):
    """Get all variables already defined in stub file"""
    defined = set()
    try:
        with open(stub_file, 'r', encoding='utf-8') as f:
            content = f.read()
            # Find all @var: definitions
            matches = re.findall(r'@([a-zA-Z_][a-zA-Z0-9_-]*)\s*:', content)
            for m in matches:
                defined.add(m)
    except Exception as e:
        print(f"Error reading stub {stub_file}: {e}", file=sys.stderr)
    return defined

def main():
    print("Scanning ele-admin-pro Less files...")
    less_files = find_less_files(ELE_ADMIN_PATH)
    print(f"Found {len(less_files)} .less files")
    
    print("Extracting variable references...")
    refs = extract_variable_references(less_files)
    print(f"Found {len(refs)} unique variable references")
    
    print("Reading defined variables from stub...")
    defined = get_defined_variables(STUB_FILE)
    print(f"Found {len(defined)} already defined variables")
    
    # Find missing variables
    missing = refs - defined
    # Filter out variables that look like JS interpolation (less.js names)
    missing = {v for v in missing if not v.startswith('_')}
    
    print(f"\nMissing variables: {len(missing)}")
    
    if not missing:
        print("All variables are defined! Nothing to do.")
        return
    
    # Generate lines to add
    lines_to_add = []
    for var in sorted(missing):
        if var in ANTDV3_DEFAULTS:
            default_val = ANTDV3_DEFAULTS[var]
            lines_to_add.append(f"@{var}: {default_val};")
        else:
            # Use empty string as default for unknown variables
            lines_to_add.append(f"@{var}: ;  // FIXME: needs proper value")
    
    print(f"\nAdding {len(lines_to_add)} variables to stub file...")
    
    # Read stub file
    with open(STUB_FILE, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Append missing variables before the end of file
    append_text = "\n// ========== Auto-added missing variables ==========\n" + "\n".join(lines_to_add) + "\n"
    
    with open(STUB_FILE, 'a', encoding='utf-8') as f:
        f.write(append_text)
    
    print("Done! Added variables:")
    for line in lines_to_add[:20]:
        print(f"  {line}")
    if len(lines_to_add) > 20:
        print(f"  ... and {len(lines_to_add) - 20} more")

if __name__ == '__main__':
    main()
