export function parsePythonToGrapes(pythonCode: string): any {
    const lines = pythonCode.split('\n');
    
    // 1. Настройки главного окна
    let rootWidth = 500;
    let rootHeight = 400;
    let rootTitle = 'Form';
    let rootBg = '#ffffff';

    const geoRegex = /root\.geometry\(['"](\d+)x(\d+)['"]\)/;
    const titleRegex = /root\.title\(['"](.*)['"]\)/;
    const bgRootRegex = /root\.configure\(bg=['"](.*)['"]\)/;

    lines.forEach(line => {
        const geo = line.match(geoRegex);
        if (geo) { rootWidth = parseInt(geo[1]); rootHeight = parseInt(geo[2]); }
        const tit = line.match(titleRegex);
        if (tit) rootTitle = tit[1];
        const bgr = line.match(bgRootRegex);
        if (bgr) rootBg = bgr[1];
    });

    // 2. Хранилища
    const widgets: { [key: string]: any } = {};
    const hierarchy: { [key: string]: string } = {};

    const creationRegex = /^\s*(\w+)\s*=\s*tk\.(\w+)\s*\(\s*([^,]+)(?:,\s*(.*))?\)/;
    const placeRegex = /^\s*(\w+)\.place\s*\(([^)]*)\)/;
    const insertRegex = /^\s*(\w+)\.insert\s*\([^,]+,\s*["'](.*)["']\)/;

    const typeMap: { [key: string]: string } = {
        'Label': 'tk-label', 'Button': 'tk-button', 'Entry': 'tk-entry',
        'Checkbutton': 'tk-check', 'Radiobutton': 'tk-radio',
        'Listbox': 'tk-listbox', 'Text': 'tk-text', 'Canvas': 'tk-canvas',
        'Frame': 'tk-frame'
    };

    const getDefaultStyle = (className: string) => {
        const base = {
            'position': 'absolute',
            'padding': '5px',
            'border': '1px solid #999',
            'background-color': '#f0f0f0',
            'display': 'flex',
            'align-items': 'center',
            'justify-content': 'center',
            'overflow': 'hidden',
            'color': 'black'
        };

        if (className === 'Entry' || className === 'Text') {
            return {
                ...base,
                'background-color': '#ffffff',
                'border': '2px inset #ccc',
                'align-items': 'flex-start',
                'justify-content': 'flex-start',
                'white-space': 'pre-wrap'
            };
        }
        if (className === 'Listbox') {
            return {
                ...base,
                'background-color': '#ffffff',
                'border': '2px inset #ccc',
                'align-items': 'flex-start',
                'justify-content': 'flex-start',
                'padding': '0'
            };
        }
        if (className === 'Frame') {
            return {
                ...base,
                'border': '2px dashed #555',
                'background-color': 'rgba(0,0,0,0.05)',
                'overflow': 'visible'
            };
        }
        if (className === 'Canvas') {
            return {
                ...base,
                'border': '1px solid black',
                'background-color': '#ffffff'
            };
        }
        // Label, Button, Checkbox...
        return base;
    };

    lines.forEach(line => {
        line = line.trim();
        if (!line || line.startsWith('#')) return;

        const createMatch = line.match(creationRegex);
        if (createMatch) {
            const varName = createMatch[1];
            const className = createMatch[2];
            const parentName = createMatch[3].trim();
            const args = createMatch[4] || '';

            if (typeMap[className]) {
                hierarchy[varName] = parentName;

                const traits: any[] = [];
                const attrs: any = { 'data-tk-type': className };
                
                const style = getDefaultStyle(className);

                const paramRegex = /(\w+)=(?:["'](.*?)["']|(\d+))/g;
                let m;
                while ((m = paramRegex.exec(args)) !== null) {
                    const key = m[1];
                    const val = m[2] || m[3];

                    if (key === 'text') traits.push({ name: 'text', value: val });
                    if (key === 'command') traits.push({ name: 'command', value: val });
                    
                    if (key === 'bg') {
                        traits.push({ name: 'bg', value: val });
                        attrs['data-bg'] = val;
                        style['background-color'] = val;
                    }
                    if (key === 'fg') {
                        traits.push({ name: 'fg', value: val });
                        attrs['data-fg'] = val;
                        style['color'] = val;
                    }
                }

                widgets[varName] = {
                    tagName: 'div',
                    type: typeMap[className],
                    attributes: attrs,
                    traits: traits,
                    components: [],
                    style: style
                };
            }
        }

        // B. Place
        const placeMatch = line.match(placeRegex);
        if (placeMatch) {
            const varName = placeMatch[1];
            const args = placeMatch[2];

            if (widgets[varName]) {
                const paramRegex = /(\w+)=(\d+)/g;
                let m;
                while ((m = paramRegex.exec(args)) !== null) {
                    const key = m[1];
                    const val = parseInt(m[2]);

                    // Обновляем CSS
                    if (key === 'x') widgets[varName].style.left = val + 'px';
                    if (key === 'y') widgets[varName].style.top = val + 'px';
                    if (key === 'width') widgets[varName].style.width = val + 'px';
                    if (key === 'height') widgets[varName].style.height = val + 'px';

                    widgets[varName].attributes[`data-${key}`] = val;
                    widgets[varName].traits.push({ name: key, value: val });
                }
            }
        }

        // C. Insert
        const insertMatch = line.match(insertRegex);
        if (insertMatch) {
            const varName = insertMatch[1];
            const textVal = insertMatch[2].replace(/\\n/g, '\n');

            if (widgets[varName]) {
                const w = widgets[varName];
                const t = w.attributes['data-tk-type'];

                if (t === 'Entry' || t === 'Text') {
                    let trait = w.traits.find((tr:any) => tr.name === 'text');
                    if (trait) trait.value = textVal;
                    else w.traits.push({ name: 'text', value: textVal });
                    w.attributes['data-text'] = textVal;
                }
                else if (t === 'Listbox') {
                    if (!w.attributes['data-items']) w.attributes['data-items'] = [];
                    w.attributes['data-items'].push(textVal);
                }
            }
        }
    });

    // 3. Сборка дерева
    const rootComponents: any[] = [];

    Object.keys(widgets).forEach(name => {
        const widget = widgets[name];
        const parent = hierarchy[name];

        if (widget.attributes['data-tk-type'] === 'Listbox' && Array.isArray(widget.attributes['data-items'])) {
            const itemsStr = widget.attributes['data-items'].join('\n');
            widget.attributes['data-items'] = itemsStr;
            widget.traits.push({ name: 'items', value: itemsStr });
            widget.traits.push({ name: 'line_count', value: widget.attributes['data-items'].length });
        }

        if (parent === 'root') {
            rootComponents.push(widget);
        } else if (widgets[parent]) {
            widgets[parent].components.push(widget);
        } else {
            rootComponents.push(widget);
        }
    });

    return {
        pages: [{
            frames: [{
                component: {
                    type: 'wrapper',
                    attributes: { 'data-width': rootWidth, 'data-height': rootHeight, 'data-title': rootTitle, 'data-bg': rootBg },
                    style: { 'background-color': rootBg, 'width': rootWidth + 'px', 'height': rootHeight + 'px', 'position': 'relative', 'overflow': 'hidden' },
                    components: rootComponents
                }
            }]
        }]
    };
}