//! Vue Dynamic Features - Inject reactive system and event handling into Vue SFC
//! Vue 动态特性 - 将响应式系统和事件处理注入到 Vue SFC

use regex::Regex;

/// Vue 动态特性注入器
pub struct VueDynamicInjector;

impl VueDynamicInjector {
    /// 注入 Vue 动态特性到 script 中
    pub fn inject_dynamic_features(script_content: &str) -> String {
        let mut enhanced_script = String::new();
        
        // 1. 添加 Iris Vue Runtime（处理 _iris 后缀元素）
        enhanced_script.push_str(Self::iris_vue_runtime());
        enhanced_script.push_str("\n\n");
        
        // 2. 添加用户原始 script
        enhanced_script.push_str(script_content);
        enhanced_script.push_str("\n\n");
        
        // 3. 添加初始化代码
        enhanced_script.push_str(Self::initialization_code());
        
        enhanced_script
    }
    
    /// 为 HTML 添加 _iris 后缀
    pub fn add_iris_suffix_to_html(html: &str) -> String {
        let mut result = html.to_string();
        
        // 匹配所有 HTML 标签（不包括已带 _iris 后缀的）
        let tag_re = Regex::new(r"<(/?)([a-zA-Z][a-zA-Z0-9-]*)([^>]*)>").unwrap();
        
        result = tag_re.replace_all(&result, |caps: &regex::Captures| {
            let slash = &caps[1];
            let tag_name = &caps[2];
            let attrs = &caps[3];
            
            // 跳过特殊标签和已带后缀的
            if tag_name.ends_with("_iris") || 
               ["template", "script", "style"].contains(&tag_name) {
                return caps[0].to_string();
            }
            
            // 添加 _iris 后缀
            format!("<{}{}_iris{}>", slash, tag_name, attrs)
        }).to_string();
        
        result
    }
    
    /// Iris Vue Runtime - 处理 _iris 后缀元素的动态特性
    fn iris_vue_runtime() -> &'static str {
        r#"
// ============================================
// Iris Vue Runtime - Dynamic Feature Handler
// ============================================

/**
 * 响应式系统（简化版 Vue reactivity）
 */
function createReactiveSystem() {
  const reactiveMap = new Map();
  
  function ref(value) {
    const wrapper = { value };
    Object.defineProperty(wrapper, 'value', {
      get() {
        return value;
      },
      set(newValue) {
        value = newValue;
        triggerUpdates();
      }
    });
    return wrapper;
  }
  
  function reactive(obj) {
    return new Proxy(obj, {
      set(target, key, value) {
        target[key] = value;
        triggerUpdates();
        return true;
      }
    });
  }
  
  function computed(fn) {
    return {
      get value() {
        return fn();
      }
    };
  }
  
  function triggerUpdates() {
    // 通知 Iris 引擎更新 DOM
    if (typeof window !== 'undefined' && window._iris_update) {
      window._iris_update();
    }
  }
  
  return { ref, reactive, computed };
}

/**
 * 事件系统 - 处理 @click 等事件绑定
 */
function createEventSystem() {
  const eventHandlers = new Map();
  
  function on(event, handler) {
    if (!eventHandlers.has(event)) {
      eventHandlers.set(event, []);
    }
    eventHandlers.get(event).push(handler);
  }
  
  function emit(event, ...args) {
    if (eventHandlers.has(event)) {
      eventHandlers.get(event).forEach(handler => handler(...args));
    }
  }
  
  // 绑定到 DOM 元素
  function bindEvents(element) {
    // 查找所有带 @click 的元素
    const clickElements = element.querySelectorAll('[\\@click]');
    clickElements.forEach(el => {
      const handlerName = el.getAttribute('@click');
      el.addEventListener('click', () => {
        if (typeof window[handlerName] === 'function') {
          window[handlerName]();
        }
      });
      el.removeAttribute('@click');
    });
  }
  
  return { on, emit, bindEvents };
}

/**
 * 模板编译器 - 处理 {{ }} 插值和 v-bind
 */
function compileTemplate(template) {
  // 处理 {{ expression }} 插值
  function processInterpolations(html) {
    const interpolationRe = /\{\{\s*(.+?)\s*\}\}/g;
    return html.replace(interpolationRe, (match, expression) => {
      try {
        // 在全局作用域执行表达式
        return eval(expression);
      } catch (e) {
        console.warn(`Failed to evaluate: ${expression}`, e);
        return match;
      }
    });
  }
  
  // 处理 v-bind:attr="value"
  function processBindings(html) {
    const bindRe = /v-bind:([a-zA-Z-]+)="([^"]+)"/g;
    return html.replace(bindRe, (match, attr, value) => {
      try {
        const evaluatedValue = eval(value);
        return `${attr}="${evaluatedValue}"`;
      } catch (e) {
        console.warn(`Failed to evaluate binding: ${value}`, e);
        return match;
      }
    });
  }
  
  return { processInterpolations, processBindings };
}

/**
 * Iris 组件生命周期
 */
function mountComponent(component) {
  const { ref, reactive, computed } = createReactiveSystem();
  const { on, emit, bindEvents } = createEventSystem();
  const { processInterpolations, processBindings } = compileTemplate();
  
  // 将 API 暴露到全局
  window.ref = ref;
  window.reactive = reactive;
  window.computed = computed;
  
  return {
    ref,
    reactive,
    computed,
    on,
    emit,
    bindEvents,
    processInterpolations,
    processBindings
  };
}

// 导出到全局
window._iris_vue_runtime = {
  createReactiveSystem,
  createEventSystem,
  compileTemplate,
  mountComponent
};
"#
    }
    
    /// 初始化代码 - 在 script setup 执行后运行
    fn initialization_code() -> &'static str {
        r#"
// ============================================
// Iris Initialization
// ============================================

(function() {
  'use strict';
  
  // 挂载 Vue 组件
  if (typeof window._iris_vue_runtime !== 'undefined') {
    const runtime = window._iris_vue_runtime.mountComponent();
    
    // 存储到全局供 Iris 引擎使用
    window._iris_component = {
      runtime,
      // 标记组件已初始化
      initialized: true,
      // 更新时间戳
      updatedAt: Date.now()
    };
    
    console.log('[Iris] Component mounted successfully');
  }
})();
"#
    }
}

/// 完整的 Vue SFC 增强处理
pub fn enhance_vue_sfc(
    template_html: &str,
    script_content: &str,
) -> (String, String) {
    // 1. 为 HTML 元素添加 _iris 后缀
    let enhanced_html = VueDynamicInjector::add_iris_suffix_to_html(template_html);
    
    // 2. 为 script 注入动态特性
    let enhanced_script = VueDynamicInjector::inject_dynamic_features(script_content);
    
    (enhanced_html, enhanced_script)
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_add_iris_suffix() {
        let html = r#"
            <div class="app">
                <h1>Title</h1>
                <button @click="handleClick">Click</button>
            </div>
        "#;
        
        let enhanced = VueDynamicInjector::add_iris_suffix_to_html(html);
        
        assert!(enhanced.contains("<div_iris"));
        assert!(enhanced.contains("<h1_iris"));
        assert!(enhanced.contains("<button_iris"));
        // 确保没有双重后缀
        assert!(!enhanced.contains("_iris_iris"));
    }
    
    #[test]
    fn test_inject_dynamic_features() {
        let script = "const count = ref(0);";
        let enhanced = VueDynamicInjector::inject_dynamic_features(script);
        
        assert!(enhanced.contains("createReactiveSystem"));
        assert!(enhanced.contains("const count = ref(0);"));
        assert!(enhanced.contains("_iris_component"));
    }
}
