//! Vue SFC 运行时相关函数
//!
//! 包含 Vue 单文件组件的加载、编译、执行等功能。
//! 这些函数仅在 `vue-sfc` feature 启用时使用。

use super::RuntimeOrchestrator;

impl RuntimeOrchestrator {
    /// 编译 SFC 模块
    #[cfg(feature = "vue-sfc")]
    fn compile_sfc<P: AsRef<std::path::Path>>(&self, path: P) -> Result<iris_sfc::SfcModule, String> {
        let p = path.as_ref();
        iris_sfc::compile(p).map_err(|e| format!("Failed to compile SFC {}: {}", p.display(), e))
    }

    /// 执行 SFC 模块
    #[cfg(feature = "vue-sfc")]
    fn execute_sfc_module(&mut self, sfc: iris_sfc::SfcModule) -> Result<(), String> {
        let specifier = format!("./{}.vue", sfc.name);

        for style_block in &sfc.styles {
            debug!(css_len = style_block.css.len(), scoped = style_block.scoped, "Injecting style...");
        }

        let transformed = self.es_modules.transform_module(&specifier, &sfc.script);
        self.js_runtime.eval(&transformed).map_err(|e| {
            format!("Failed to execute SFC script: {}", e)
        })
    }

    /// 预加载 SFC 依赖
    #[cfg(feature = "vue-sfc")]
    fn preload_sfc_dependencies(&mut self, sfc: &iris_sfc::SfcModule) -> Result<(), String> {
        let imports = self.es_modules.parse_imports(&sfc.script);
        info!("Preload: found {} imports in script", imports.len());
        for import_specifier in &imports {
            if import_specifier.ends_with(".vue") && import_specifier.starts_with(".") {
                let resolved = std::path::Path::new(".").join(import_specifier);
                if resolved.exists() {
                    info!("Pre-loading sub-component: {} -> {}", import_specifier, resolved.display());
                    match self.compile_sfc(&resolved) {
                        Ok(sub_module) => {
                            if let Err(e) = self.execute_sfc_module(sub_module, import_specifier) {
                                info!("Failed to pre-load sub-component: {}", e);
                            }
                        }
                        Err(e) => info!("Failed to compile sub-component: {}", e),
                    }
                }
            }
        }
        Ok(())
    }

    /// 从响应式更新 VTree
    #[cfg(feature = "vue-sfc")]
    pub fn update_vtree_from_reactive(&mut self) -> Result<(), String> {
        info!("Updating VTree from reactive state...");

        let _root_id = iris_js::vue::get_vtree_from_runtime(
            &mut self.js_runtime,
            &mut self.es_modules,
        ).map_err(|e| format!("Failed to get VTree from runtime: {}", e))?;

        let js_code = format!(
            r#"
            let root = __render_root_id;
            if (__vnode_map && root) {{
                JSON.stringify(__vnode_map[root]);
            }}
            "#
        );
        self.js_runtime.eval(&js_code).map_err(|e| format!("Reactive render failed: {}", e))?;

        info!("VTree updated from reactive state");
        Ok(())
    }

    /// 加载 SFC 并构建 VTree
    #[cfg(feature = "vue-sfc")]
    pub fn load_sfc_with_vtree<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<(), String> {
        let path = path.as_ref();
        info!(path = ?path, "Loading SFC with VTree...");

        let sfc_module = self.compile_sfc(path)?;
        info!(name = %sfc_module.name, "SFC compiled");

        let specifier = format!("./{}", path.file_name().unwrap_or_default().to_string_lossy());
        self.execute_sfc_module(sfc_module, &specifier)?;
        info!("SFC module executed");

        let vtree = iris_js::vue::get_vtree_from_runtime(
            &mut self.js_runtime,
            &mut self.es_modules,
        ).map_err(|e| format!("Failed to get VTree: {}", e))?;

        self.vtree = Some(vtree);
        info!("VTree generated from SFC");

        Ok(())
    }

    /// 从文件构建 VTree
    #[cfg(feature = "vue-sfc")]
    fn build_vtree_from_file<P: AsRef<std::path::Path>>(&self, _path: P) -> Result<iris_layout::vdom::VTree, String> {
        Err("build_vtree_from_file not implemented in refactored path".to_string())
    }

    /// 简单模板解析
    #[cfg(feature = "vue-sfc")]
    fn simple_parse_template(_template: &str) -> iris_layout::vdom::VTree {
        panic!("simple_parse_template has been removed. Use load_sfc_with_vtree() instead.")
    }

    /// 转换 Handle 到 DOMNode
    #[cfg(feature = "vue-sfc")]
    fn convert_handle_to_dom_node(&self, _handle: u64) -> Option<iris_layout::dom::DOMNode> {
        None
    }

    /// 检查节点是否为空
    #[cfg(feature = "vue-sfc")]
    fn is_empty_node(&self, node: &iris_layout::dom::DOMNode) -> bool {
        node.children.is_empty() && node.tag != "#text"
    }
}