'use strict';

var SceneImporter = require('./SceneImporter.js');

/**
 * @file GodotSceneImporter.ts
 * @description Import Godot scenes (.tscn) and resources (.tres)
 * PRO-1.3: Scene Format Interoperability
 *
 * Parses Godot 4.x scene format and converts to Nice2Dev entities.
 * Supports:
 * - Scene files (.tscn)
 * - Resource files (.tres)
 * - Project files (.godot)
 */
// ============================================================
// Godot Node Types Mapping
// ============================================================
const GODOT_NODE_MAPPING = {
    // 2D Nodes
    Node2D: { niceType: 'Transform2D', category: '2d' },
    Sprite2D: { niceType: 'Sprite', category: '2d' },
    AnimatedSprite2D: { niceType: 'AnimatedSprite', category: '2d' },
    CharacterBody2D: { niceType: 'CharacterController2D', category: '2d' },
    RigidBody2D: { niceType: 'Rigidbody2D', category: '2d' },
    StaticBody2D: { niceType: 'StaticBody2D', category: '2d' },
    Area2D: { niceType: 'Trigger2D', category: '2d' },
    CollisionShape2D: { niceType: 'Collider2D', category: '2d' },
    CollisionPolygon2D: { niceType: 'PolygonCollider2D', category: '2d' },
    TileMap: { niceType: 'Tilemap', category: '2d' },
    TileMapLayer: { niceType: 'TilemapLayer', category: '2d' },
    Camera2D: { niceType: 'Camera2D', category: '2d' },
    Light2D: { niceType: 'Light2D', category: '2d' },
    PointLight2D: { niceType: 'PointLight2D', category: '2d' },
    DirectionalLight2D: { niceType: 'DirectionalLight2D', category: '2d' },
    Line2D: { niceType: 'LineRenderer', category: '2d' },
    Path2D: { niceType: 'Path2D', category: '2d' },
    PathFollow2D: { niceType: 'PathFollower2D', category: '2d' },
    GPUParticles2D: { niceType: 'ParticleSystem2D', category: '2d' },
    CPUParticles2D: { niceType: 'CPUParticles2D', category: '2d' },
    // 3D Nodes
    Node3D: { niceType: 'Transform3D', category: '3d' },
    MeshInstance3D: { niceType: 'MeshRenderer', category: '3d' },
    CharacterBody3D: { niceType: 'CharacterController3D', category: '3d' },
    RigidBody3D: { niceType: 'Rigidbody3D', category: '3d' },
    StaticBody3D: { niceType: 'StaticBody3D', category: '3d' },
    Area3D: { niceType: 'Trigger3D', category: '3d' },
    CollisionShape3D: { niceType: 'Collider3D', category: '3d' },
    Camera3D: { niceType: 'Camera3D', category: '3d' },
    DirectionalLight3D: { niceType: 'DirectionalLight', category: '3d' },
    OmniLight3D: { niceType: 'PointLight', category: '3d' },
    SpotLight3D: { niceType: 'SpotLight', category: '3d' },
    GPUParticles3D: { niceType: 'ParticleSystem3D', category: '3d' },
    // Audio
    AudioStreamPlayer: { niceType: 'AudioSource', category: 'audio' },
    AudioStreamPlayer2D: { niceType: 'AudioSource2D', category: 'audio' },
    AudioStreamPlayer3D: { niceType: 'AudioSource3D', category: 'audio' },
    // UI
    Control: { niceType: 'UIElement', category: 'ui' },
    Label: { niceType: 'Text', category: 'ui' },
    Button: { niceType: 'Button', category: 'ui' },
    TextureRect: { niceType: 'Image', category: 'ui' },
    Panel: { niceType: 'Panel', category: 'ui' },
    HBoxContainer: { niceType: 'HorizontalLayout', category: 'ui' },
    VBoxContainer: { niceType: 'VerticalLayout', category: 'ui' },
    GridContainer: { niceType: 'GridLayout', category: 'ui' },
    ScrollContainer: { niceType: 'ScrollView', category: 'ui' },
    LineEdit: { niceType: 'InputField', category: 'ui' },
    TextEdit: { niceType: 'TextArea', category: 'ui' },
    CheckBox: { niceType: 'Checkbox', category: 'ui' },
    ProgressBar: { niceType: 'ProgressBar', category: 'ui' },
    Slider: { niceType: 'Slider', category: 'ui' },
    SpinBox: { niceType: 'SpinBox', category: 'ui' },
    ColorRect: { niceType: 'ColorPanel', category: 'ui' },
    NinePatchRect: { niceType: 'NineSlice', category: 'ui' },
    CanvasLayer: { niceType: 'UICanvas', category: 'ui' },
    // Animation
    AnimationPlayer: { niceType: 'Animator', category: 'animation' },
    AnimationTree: { niceType: 'AnimationStateMachine', category: 'animation' },
    // Navigation
    NavigationRegion2D: { niceType: 'NavMesh2D', category: 'navigation' },
    NavigationAgent2D: { niceType: 'NavAgent2D', category: 'navigation' },
    NavigationRegion3D: { niceType: 'NavMesh3D', category: 'navigation' },
    NavigationAgent3D: { niceType: 'NavAgent3D', category: 'navigation' },
    // Other
    Timer: { niceType: 'Timer', category: 'utility' },
    HTTPRequest: { niceType: 'HTTPClient', category: 'utility' },
};
// ============================================================
// Godot Scene Importer
// ============================================================
class GodotSceneImporter extends SceneImporter.SceneImporter {
    constructor() {
        super('godot');
        this.extResources = new Map();
        this.subResources = new Map();
        this.nodes = [];
        this.connections = [];
        this.header = {};
    }
    async import(options) {
        const startTime = Date.now();
        this.options = options;
        this.clearMessages();
        this.extResources.clear();
        this.subResources.clear();
        this.nodes = [];
        this.connections = [];
        const errors = await this.validate(options.sourcePath);
        if (errors.some((e) => e.fatal)) {
            return {
                ...this.createEmptyResult(),
                errors: errors,
            };
        }
        const scenes = [];
        const assets = [];
        try {
            const content = await this.readFile(options.sourcePath);
            const parsed = this.parseGodotScene(content, options.sourcePath);
            if (parsed) {
                const niceScene = this.convertParsedToNiceScene(parsed);
                scenes.push(niceScene);
                const extractedAssets = this.extractAssets();
                assets.push(...extractedAssets);
            }
        }
        catch (error) {
            this.addError('IMPORT_ERROR', `Failed to import: ${error}`, options.sourcePath, undefined, true);
        }
        return this.createResult(scenes, assets, startTime);
    }
    async parseFile(content, filePath) {
        const stringContent = typeof content === 'string' ? content : new TextDecoder().decode(content);
        return this.parseGodotScene(stringContent, filePath);
    }
    async validate(sourcePath) {
        const errors = [];
        if (!this.canHandle(sourcePath)) {
            errors.push({
                code: 'INVALID_FORMAT',
                message: `File ${sourcePath} is not a valid Godot file`,
                file: sourcePath,
                fatal: true,
            });
        }
        return errors;
    }
    // ----------------------------------------
    // Godot Parsing
    // ----------------------------------------
    parseGodotScene(content, filePath) {
        const lines = content.split('\n');
        let currentSection = null;
        let currentItem = {};
        let bracketDepth = 0;
        let multilineKey = '';
        let multilineValue = '';
        for (const line of lines) {
            const trimmed = line.trim();
            // Skip empty lines and comments
            if (trimmed === '' || trimmed.startsWith(';'))
                continue;
            // Check for section headers
            const sectionMatch = trimmed.match(/^\[(\w+)(.*?)\]$/);
            if (sectionMatch) {
                // Save previous item
                this.saveCurrentItem(currentSection, currentItem);
                currentItem = {};
                const sectionType = sectionMatch[1];
                const sectionParams = sectionMatch[2].trim();
                if (sectionType === 'gd_scene' || sectionType === 'gd_resource') {
                    currentSection = 'header';
                    this.header = this.parseInlineParams(sectionParams);
                }
                else if (sectionType === 'ext_resource') {
                    currentSection = 'ext_resource';
                    currentItem = this.parseInlineParams(sectionParams);
                }
                else if (sectionType === 'sub_resource') {
                    currentSection = 'sub_resource';
                    currentItem = this.parseInlineParams(sectionParams);
                }
                else if (sectionType === 'node') {
                    currentSection = 'node';
                    currentItem = this.parseInlineParams(sectionParams);
                }
                else if (sectionType === 'connection') {
                    currentSection = 'connection';
                    currentItem = this.parseInlineParams(sectionParams);
                }
                continue;
            }
            // Handle multiline values
            if (multilineKey) {
                multilineValue += '\n' + line;
                bracketDepth += (line.match(/[\[\{]/g) || []).length;
                bracketDepth -= (line.match(/[\]\}]/g) || []).length;
                if (bracketDepth === 0) {
                    currentItem[multilineKey] = this.parseGodotValue(multilineValue);
                    multilineKey = '';
                    multilineValue = '';
                }
                continue;
            }
            // Parse property assignment
            const propMatch = trimmed.match(/^(\w+)\s*=\s*(.*)$/);
            if (propMatch) {
                const key = propMatch[1];
                const value = propMatch[2];
                // Check if value starts multiline
                bracketDepth = (value.match(/[\[\{]/g) || []).length;
                bracketDepth -= (value.match(/[\]\}]/g) || []).length;
                if (bracketDepth > 0) {
                    multilineKey = key;
                    multilineValue = value;
                }
                else {
                    currentItem[key] = this.parseGodotValue(value);
                }
            }
        }
        // Save final item
        this.saveCurrentItem(currentSection, currentItem);
        // Build scene structure
        const sceneName = filePath.substring(filePath.lastIndexOf('/') + 1).replace(/\.\w+$/, '');
        // Find root node
        const rootNode = this.nodes.find((n) => !n.parent);
        return {
            name: sceneName,
            width: 1920,
            height: 1080,
            backgroundColor: '#1a1a2e',
            layers: [],
            entities: rootNode ? [this.convertNodeToEntity(rootNode)] : [],
            properties: {
                godotVersion: this.header.gdVersion,
                format: this.header.format,
                loadSteps: this.header.loadSteps,
            },
        };
    }
    saveCurrentItem(section, item) {
        if (!section || Object.keys(item).length === 0)
            return;
        switch (section) {
            case 'ext_resource':
                const extRes = {
                    id: String(item.id || ''),
                    type: String(item.type || ''),
                    path: String(item.path || ''),
                    uid: item.uid ? String(item.uid) : undefined,
                };
                this.extResources.set(extRes.id, extRes);
                break;
            case 'sub_resource':
                const subRes = {
                    id: String(item.id || ''),
                    type: String(item.type || ''),
                    properties: { ...item },
                };
                delete subRes.properties.id;
                delete subRes.properties.type;
                this.subResources.set(subRes.id, subRes);
                break;
            case 'node':
                const node = {
                    name: String(item.name || ''),
                    type: item.type ? String(item.type) : undefined,
                    parent: item.parent ? String(item.parent) : undefined,
                    instance: item.instance ? String(item.instance) : undefined,
                    instancePlaceholder: item.instance_placeholder
                        ? String(item.instance_placeholder)
                        : undefined,
                    owner: item.owner ? String(item.owner) : undefined,
                    index: item.index ? Number(item.index) : undefined,
                    groups: item.groups ? item.groups : undefined,
                    properties: {},
                    children: [],
                };
                // Copy remaining properties
                for (const [key, value] of Object.entries(item)) {
                    if (![
                        'name',
                        'type',
                        'parent',
                        'instance',
                        'instance_placeholder',
                        'owner',
                        'index',
                        'groups',
                    ].includes(key)) {
                        node.properties[key] = value;
                    }
                }
                this.nodes.push(node);
                break;
            case 'connection':
                const conn = {
                    signal: String(item.signal || ''),
                    from: String(item.from || ''),
                    to: String(item.to || ''),
                    method: String(item.method || ''),
                    flags: item.flags ? Number(item.flags) : undefined,
                    binds: item.binds,
                };
                this.connections.push(conn);
                break;
        }
    }
    parseInlineParams(params) {
        const result = {};
        // Parse space-separated key=value pairs
        const paramRegex = /(\w+)=("(?:[^"\\]|\\.)*"|[^\s]+)/g;
        let match;
        while ((match = paramRegex.exec(params)) !== null) {
            const key = match[1];
            let value = match[2];
            // Remove quotes
            if (value.startsWith('"') && value.endsWith('"')) {
                value = value.slice(1, -1).replace(/\\"/g, '"');
            }
            result[key] = this.parseGodotValue(value);
        }
        return result;
    }
    parseGodotValue(value) {
        value = value.trim();
        // Null
        if (value === 'null')
            return null;
        // Boolean
        if (value === 'true')
            return true;
        if (value === 'false')
            return false;
        // Number
        if (/^-?\d+$/.test(value))
            return parseInt(value, 10);
        if (/^-?\d+\.\d+$/.test(value))
            return parseFloat(value);
        // String
        if (value.startsWith('"') && value.endsWith('"')) {
            return value.slice(1, -1).replace(/\\"/g, '"').replace(/\\n/g, '\n');
        }
        // Vector2
        const vec2Match = value.match(/^Vector2\s*\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)$/);
        if (vec2Match) {
            return {
                _type: 'Vector2',
                x: parseFloat(vec2Match[1]),
                y: parseFloat(vec2Match[2]),
            };
        }
        // Vector3
        const vec3Match = value.match(/^Vector3\s*\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)$/);
        if (vec3Match) {
            return {
                _type: 'Vector3',
                x: parseFloat(vec3Match[1]),
                y: parseFloat(vec3Match[2]),
                z: parseFloat(vec3Match[3]),
            };
        }
        // Rect2
        const rect2Match = value.match(/^Rect2\s*\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)$/);
        if (rect2Match) {
            return {
                _type: 'Rect2',
                x: parseFloat(rect2Match[1]),
                y: parseFloat(rect2Match[2]),
                width: parseFloat(rect2Match[3]),
                height: parseFloat(rect2Match[4]),
            };
        }
        // Color
        const colorMatch = value.match(/^Color\s*\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*(?:,\s*([\d.-]+))?\s*\)$/);
        if (colorMatch) {
            return {
                _type: 'Color',
                r: parseFloat(colorMatch[1]),
                g: parseFloat(colorMatch[2]),
                b: parseFloat(colorMatch[3]),
                a: colorMatch[4] ? parseFloat(colorMatch[4]) : 1.0,
            };
        }
        // ExtResource
        const extResMatch = value.match(/^ExtResource\s*\(\s*"?(\d+)"?\s*\)$/);
        if (extResMatch) {
            return { _type: 'ExtResource', id: extResMatch[1] };
        }
        // SubResource
        const subResMatch = value.match(/^SubResource\s*\(\s*"?(\d+)"?\s*\)$/);
        if (subResMatch) {
            return { _type: 'SubResource', id: subResMatch[1] };
        }
        // Array
        if (value.startsWith('[') && value.endsWith(']')) {
            return this.parseGodotArray(value);
        }
        // Dictionary
        if (value.startsWith('{') && value.endsWith('}')) {
            return this.parseGodotDictionary(value);
        }
        // Unquoted string
        return value;
    }
    parseGodotArray(value) {
        const content = value.slice(1, -1).trim();
        if (!content)
            return [];
        const items = [];
        let depth = 0;
        let current = '';
        for (let i = 0; i < content.length; i++) {
            const char = content[i];
            if (char === '[' || char === '{' || char === '(')
                depth++;
            else if (char === ']' || char === '}' || char === ')')
                depth--;
            if (char === ',' && depth === 0) {
                items.push(this.parseGodotValue(current.trim()));
                current = '';
            }
            else {
                current += char;
            }
        }
        if (current.trim()) {
            items.push(this.parseGodotValue(current.trim()));
        }
        return items;
    }
    parseGodotDictionary(value) {
        const content = value.slice(1, -1).trim();
        if (!content)
            return {};
        const result = {};
        let depth = 0;
        let current = '';
        let key = '';
        let inKey = true;
        for (let i = 0; i < content.length; i++) {
            const char = content[i];
            if (char === '[' || char === '{' || char === '(')
                depth++;
            else if (char === ']' || char === '}' || char === ')')
                depth--;
            if (char === ':' && depth === 0 && inKey) {
                key = current.trim().replace(/^"|"$/g, '');
                current = '';
                inKey = false;
            }
            else if (char === ',' && depth === 0) {
                result[key] = this.parseGodotValue(current.trim());
                current = '';
                key = '';
                inKey = true;
            }
            else {
                current += char;
            }
        }
        if (key && current.trim()) {
            result[key] = this.parseGodotValue(current.trim());
        }
        return result;
    }
    convertNodeToEntity(node) {
        const mapping = GODOT_NODE_MAPPING[node.type || ''] || {
            niceType: node.type || 'Node',
            category: 'unknown',
        };
        // Find children
        const children = this.nodes.filter((n) => {
            if (!n.parent)
                return false;
            // Parent is "." means direct child of root
            if (n.parent === '.')
                return node.parent === undefined;
            // Match by path
            return n.parent === node.name || n.parent.endsWith('/' + node.name);
        });
        // Extract position and rotation
        const position = this.extractVector2(node.properties.position) || { x: 0, y: 0 };
        const rotation = typeof node.properties.rotation === 'number' ? node.properties.rotation * (180 / Math.PI) : 0;
        const scale = this.extractVector2(node.properties.scale) || { x: 1, y: 1 };
        // Build components
        const components = [];
        components.push(this.convertGodotNodeToComponent(node));
        // Add script component if present
        if (node.properties.script) {
            components.push({
                type: 'Script',
                data: {
                    script: node.properties.script,
                    scriptType: 'gdscript',
                },
            });
        }
        return {
            id: this.generateId(),
            name: node.name,
            type: mapping.niceType,
            x: position.x,
            y: position.y,
            width: 1,
            height: 1,
            rotation,
            scaleX: scale.x,
            scaleY: scale.y,
            visible: node.properties.visible !== false,
            components,
            children: children.map((c) => this.convertNodeToEntity(c)),
            properties: {
                godotType: node.type,
                category: mapping.category,
                groups: node.groups,
                ...node.properties,
            },
        };
    }
    convertGodotNodeToComponent(node) {
        var _a, _b, _c, _d, _e, _f, _g;
        const type = node.type || 'Node';
        switch (type) {
            case 'Sprite2D':
                return {
                    type: 'Sprite',
                    data: {
                        texture: node.properties.texture,
                        centered: node.properties.centered !== false,
                        offset: this.extractVector2(node.properties.offset),
                        flipH: node.properties.flip_h || false,
                        flipV: node.properties.flip_v || false,
                        hframes: node.properties.hframes || 1,
                        vframes: node.properties.vframes || 1,
                        frame: node.properties.frame || 0,
                        modulate: node.properties.modulate,
                    },
                };
            case 'AnimatedSprite2D':
                return {
                    type: 'AnimatedSprite',
                    data: {
                        spriteFrames: node.properties.sprite_frames,
                        animation: node.properties.animation,
                        frame: node.properties.frame || 0,
                        playing: node.properties.playing || false,
                        speedScale: node.properties.speed_scale || 1.0,
                        centered: node.properties.centered !== false,
                        offset: this.extractVector2(node.properties.offset),
                        flipH: node.properties.flip_h || false,
                        flipV: node.properties.flip_v || false,
                    },
                };
            case 'CharacterBody2D':
                return {
                    type: 'CharacterController2D',
                    data: {
                        motionMode: node.properties.motion_mode || 0,
                        upDirection: this.extractVector2(node.properties.up_direction) || { x: 0, y: -1 },
                        floorStopOnSlope: node.properties.floor_stop_on_slope || true,
                        floorMaxAngle: node.properties.floor_max_angle || 0.785398,
                        platformOnLeave: node.properties.platform_on_leave || 0,
                        safeMargin: node.properties.safe_margin || 0.08,
                    },
                };
            case 'RigidBody2D':
                return {
                    type: 'Rigidbody2D',
                    data: {
                        mass: node.properties.mass || 1.0,
                        physicsMaterialOverride: node.properties.physics_material_override,
                        gravityScale: (_a = node.properties.gravity_scale) !== null && _a !== void 0 ? _a : 1.0,
                        freezeMode: node.properties.freeze_mode || 0,
                        freeze: node.properties.freeze || false,
                        customIntegrator: node.properties.custom_integrator || false,
                        continuousCd: node.properties.continuous_cd || 0,
                        linearVelocity: this.extractVector2(node.properties.linear_velocity),
                        angularVelocity: node.properties.angular_velocity || 0,
                        linearDamp: node.properties.linear_damp || 0,
                        angularDamp: node.properties.angular_damp || 0,
                    },
                };
            case 'CollisionShape2D':
                return {
                    type: 'Collider2D',
                    data: {
                        shape: node.properties.shape,
                        disabled: node.properties.disabled || false,
                        oneWayCollision: node.properties.one_way_collision || false,
                        oneWayCollisionMargin: node.properties.one_way_collision_margin || 1.0,
                    },
                };
            case 'Area2D':
                return {
                    type: 'Trigger2D',
                    data: {
                        monitorable: (_b = node.properties.monitorable) !== null && _b !== void 0 ? _b : true,
                        monitoring: (_c = node.properties.monitoring) !== null && _c !== void 0 ? _c : true,
                        priority: node.properties.priority || 0,
                        collisionLayer: node.properties.collision_layer,
                        collisionMask: node.properties.collision_mask,
                        gravitySpaceOverride: node.properties.gravity_space_override,
                        gravityPointCenter: this.extractVector2(node.properties.gravity_point_center),
                        gravity: node.properties.gravity,
                    },
                };
            case 'Camera2D':
                return {
                    type: 'Camera2D',
                    data: {
                        enabled: (_d = node.properties.enabled) !== null && _d !== void 0 ? _d : true,
                        zoom: this.extractVector2(node.properties.zoom) || { x: 1, y: 1 },
                        offset: this.extractVector2(node.properties.offset),
                        anchorMode: node.properties.anchor_mode || 1,
                        rotationSmoothingEnabled: node.properties.rotation_smoothing_enabled || false,
                        positionSmoothingEnabled: node.properties.position_smoothing_enabled || false,
                        positionSmoothingSpeed: node.properties.position_smoothing_speed || 5,
                        limitLeft: node.properties.limit_left,
                        limitTop: node.properties.limit_top,
                        limitRight: node.properties.limit_right,
                        limitBottom: node.properties.limit_bottom,
                        limitSmoothed: node.properties.limit_smoothed || false,
                    },
                };
            case 'TileMap':
            case 'TileMapLayer':
                return {
                    type: 'Tilemap',
                    data: {
                        tileSet: node.properties.tile_set,
                        cellSize: this.extractVector2(node.properties.cell_size) || { x: 16, y: 16 },
                        quadrantSize: node.properties.quadrant_size || 16,
                        format: node.properties.format,
                        tileData: node.properties.tile_data || node.properties.layer_0 || node.properties.layer0,
                    },
                };
            case 'AudioStreamPlayer':
            case 'AudioStreamPlayer2D':
            case 'AudioStreamPlayer3D':
                return {
                    type: 'AudioSource',
                    data: {
                        stream: node.properties.stream,
                        volumeDb: node.properties.volume_db || 0,
                        pitchScale: node.properties.pitch_scale || 1.0,
                        playing: node.properties.playing || false,
                        autoplay: node.properties.autoplay || false,
                        bus: node.properties.bus || 'Master',
                        maxDistance: node.properties.max_distance,
                        attenuation: node.properties.attenuation,
                    },
                };
            case 'AnimationPlayer':
                return {
                    type: 'Animator',
                    data: {
                        rootNode: node.properties.root_node,
                        autoplay: node.properties.autoplay,
                        currentAnimation: node.properties.current_animation,
                        playbackSpeed: node.properties.playback_speed || 1.0,
                        libraries: node.properties.libraries,
                    },
                };
            case 'GPUParticles2D':
            case 'CPUParticles2D':
                return {
                    type: 'ParticleSystem2D',
                    data: {
                        emitting: (_e = node.properties.emitting) !== null && _e !== void 0 ? _e : true,
                        amount: node.properties.amount || 8,
                        lifetime: node.properties.lifetime || 1.0,
                        oneShot: node.properties.one_shot || false,
                        preprocess: node.properties.preprocess || 0,
                        speedScale: node.properties.speed_scale || 1.0,
                        explosiveness: node.properties.explosiveness || 0,
                        randomness: node.properties.randomness || 0,
                        texture: node.properties.texture,
                        processMaterial: node.properties.process_material,
                    },
                };
            case 'Light2D':
            case 'PointLight2D':
                return {
                    type: 'Light2D',
                    data: {
                        enabled: (_f = node.properties.enabled) !== null && _f !== void 0 ? _f : true,
                        color: node.properties.color,
                        energy: (_g = node.properties.energy) !== null && _g !== void 0 ? _g : 1.0,
                        texture: node.properties.texture,
                        textureScale: node.properties.texture_scale || 1.0,
                        blendMode: node.properties.blend_mode || 0,
                        shadowEnabled: node.properties.shadow_enabled || false,
                        shadowColor: node.properties.shadow_color,
                    },
                };
            case 'Label':
                return {
                    type: 'Text',
                    data: {
                        text: node.properties.text || '',
                        horizontalAlignment: node.properties.horizontal_alignment || 0,
                        verticalAlignment: node.properties.vertical_alignment || 0,
                        autowrapMode: node.properties.autowrap_mode || 0,
                        clipText: node.properties.clip_text || false,
                        textOverrunBehavior: node.properties.text_overrun_behavior || 0,
                        theme: node.properties.theme,
                        themeOverride: node.properties.theme_override_colors || node.properties.theme_override_fonts,
                    },
                };
            case 'Button':
                return {
                    type: 'Button',
                    data: {
                        text: node.properties.text || '',
                        disabled: node.properties.disabled || false,
                        flat: node.properties.flat || false,
                        icon: node.properties.icon,
                        toggleMode: node.properties.toggle_mode || false,
                        buttonPressed: node.properties.button_pressed || false,
                    },
                };
            default:
                return {
                    type: type,
                    data: { ...node.properties },
                };
        }
    }
    extractVector2(value) {
        if (!value)
            return undefined;
        if (typeof value === 'object' && value !== null) {
            if ('_type' in value && value._type === 'Vector2') {
                return { x: value.x, y: value.y };
            }
            if ('x' in value && 'y' in value) {
                return {
                    x: Number(value.x),
                    y: Number(value.y),
                };
            }
        }
        return undefined;
    }
    extractAssets() {
        var _a;
        const assets = [];
        for (const [id, extRes] of this.extResources) {
            let assetType = 'data';
            // Determine asset type from Godot resource type
            switch (extRes.type) {
                case 'Texture2D':
                case 'CompressedTexture2D':
                case 'AtlasTexture':
                case 'ImageTexture':
                    assetType = 'texture';
                    break;
                case 'AudioStream':
                case 'AudioStreamMP3':
                case 'AudioStreamOGGVorbis':
                case 'AudioStreamWAV':
                    assetType = 'audio';
                    break;
                case 'SpriteFrames':
                case 'Animation':
                case 'AnimationLibrary':
                    assetType = 'animation';
                    break;
                case 'TileSet':
                    assetType = 'tileset';
                    break;
                case 'Script':
                case 'GDScript':
                case 'CSharpScript':
                    assetType = 'script';
                    break;
                case 'Shader':
                case 'VisualShader':
                    assetType = 'shader';
                    break;
                case 'Font':
                case 'FontFile':
                case 'SystemFont':
                    assetType = 'font';
                    break;
            }
            assets.push({
                id: this.generateId(),
                name: ((_a = extRes.path
                    .split('/')
                    .pop()) === null || _a === void 0 ? void 0 : _a.replace(/\.\w+$/, '')) || `resource_${id}`,
                type: assetType,
                path: extRes.path,
                data: {
                    godotType: extRes.type,
                    extResourceId: id,
                    uid: extRes.uid,
                },
            });
        }
        return assets;
    }
    // ----------------------------------------
    // Helper Methods
    // ----------------------------------------
    async readFile(path) {
        var _a;
        if (typeof globalThis.process !== 'undefined' && ((_a = globalThis.process.versions) === null || _a === void 0 ? void 0 : _a.node)) {
            const fs = await import('fs');
            return fs.readFileSync(path, 'utf-8');
        }
        else if (typeof fetch !== 'undefined') {
            const response = await fetch(path);
            return response.text();
        }
        throw new Error('Unable to read file in current environment');
    }
}

exports.GodotSceneImporter = GodotSceneImporter;
//# sourceMappingURL=GodotSceneImporter.js.map
