/**
 * PythonPluginLoader - Python 插件加载器
 * 通过 python_execute 工具执行 Python 插件
 */

const fs = require('fs')
const path = require('path')
const { Plugin } = require('../src/core/plugin-base')
const { logger } = require('../src/utils/logger')
const log = logger.child('PythonPluginLoader')
const { z } = require('zod')
const { zodSchemaToMarkdown } = require('@chnak/zod-to-markdown')

// 将 JSON Schema 转换为 Zod Schema
function jsonSchemaToZod(jsonSchema) {
  if (!jsonSchema || jsonSchema.type !== 'object') {
    return z.object({})
  }

  const properties = jsonSchema.properties || {}
  const required = jsonSchema.required || []

  const shape = {}
  for (const [key, prop] of Object.entries(properties)) {
    let zodType
    switch (prop.type) {
      case 'string':
        zodType = z.string()
        break
      case 'number':
        zodType = z.number()
        break
      case 'boolean':
        zodType = z.boolean()
        break
      case 'array':
        zodType = z.array(z.any())
        break
      case 'object':
        zodType = jsonSchemaToZod(prop)
        break
      default:
        zodType = z.any()
    }
    // 如果不是 required 字段，则标记为 optional
    if (!required.includes(key)) {
      zodType = zodType.optional()
    }
    shape[key] = zodType
  }

  return z.object(shape)
}

class PythonPluginLoader extends Plugin {
  constructor(config = {}) {
    super()
    this.name = 'python-plugin-loader'
    this.version = '1.0.0'
    this.description = 'Python 插件加载器，属于Python的插件'

    this._agentDir = config.agentDir || '.agent'
    this._pythonPlugins = new Map()
    this._framework = null
    this.system = true 
  }

  install(framework) {
    this._framework = framework
    return this
  }

  start(framework) {
    // 先设置 framework 引用（供 _loadPythonPlugins 使用）
    this._framework = framework

    // 加载所有 Python 插件（会注册工具到 ExtensionExecutor）
    this._loadPythonPlugins()

    // 监听 agent 创建事件，附加 Python 插件信息到系统提示词
    framework.on('agent:created', (agent) => {
      this._refreshAgentPythonPluginsPrompt(agent)
    })

    // 等待框架就绪后，刷新所有已有 agent 的 Python 插件提示词
    if (framework._ready) {
      this._refreshAllAgentsPythonPluginsPrompt(framework)
    } else {
      framework.once('framework:ready', () => {
        this._refreshAllAgentsPythonPluginsPrompt(framework)
      })
    }

    return this
  }

  /**
   * 构建 Python 插件描述
   */
  _buildPythonPluginsDescription() {
    if (this._pythonPlugins.size === 0) {
      return ''
    }

    let desc = '## 【Python 插件】\n'
    desc += 'Python 插件工具已注册为 `插件名_工具名` 格式，通过 ext_call 调用：\n\n'

    for (const [name, plugin] of this._pythonPlugins) {
      desc += `### ${plugin.info.name}\n`
      desc += `${plugin.info.description || ''}\n\n`
      if (plugin.info.tools && Array.isArray(plugin.info.tools)) {
        for (const tool of plugin.info.tools) {
          const fullName = `${name}_${tool.name}`
          const paramsStr = this._formatParams(tool.params || {})
          desc += `- **${fullName}**(${paramsStr}): ${tool.description || '无描述'}\n`
        }
      }
      desc += '\n'
    }

    desc += '**调用格式:**\n'
    desc += '```\next_call({ plugin: "python", tool: "插件名_工具名", args: {...} })\n'
    desc += '```\n'
    return desc.trim()
  }

  /**
   * 刷新单个 agent 的 Python 插件提示词
   */
  _refreshAgentPythonPluginsPrompt(agent) {
    const existingPrompt = agent._originalPrompt || ''
    if (existingPrompt.includes('【Python 插件】')) {
      return
    }

    const pyDesc = this._buildPythonPluginsDescription()
    if (!pyDesc) return

    // 将 Python 插件描述追加到系统提示词
    agent.setSystemPrompt(existingPrompt + '\n\n' + pyDesc)
  }

  /**
   * 刷新所有 agent 的 Python 插件提示词
   */
  _refreshAllAgentsPythonPluginsPrompt(framework) {
    const visited = new Set()

    const traverse = (agent) => {
      if (!agent || visited.has(agent)) return
      visited.add(agent)
      this._refreshAgentPythonPluginsPrompt(agent)

      // 递归处理子 agent
      const subAgents = agent.getSubAgents?.() || agent._subAgents || new Map()
      for (const [name, subAgentInfo] of subAgents) {
        traverse(subAgentInfo.agent)
      }
    }

    const agents = framework._agents || []
    for (const agent of agents) {
      traverse(agent)
    }
  }

  /**
   * 加载所有 Python 插件
   */
  _loadPythonPlugins() {
    const pluginsDir = path.join(this._agentDir, 'plugins')
    if (!fs.existsSync(pluginsDir)) {
      return
    }

    const files = fs.readdirSync(pluginsDir).filter(f => f.endsWith('.py'))

    for (const file of files) {
      try {
        const pluginPath = path.join(pluginsDir, file)
        const pluginName = file.replace('.py', '')

        const pluginInfo = this._loadPythonPluginMeta(pluginPath)
        if (pluginInfo) {
          this._pythonPlugins.set(pluginName, {
            name: pluginName,
            path: pluginPath,
            info: pluginInfo,
            code: fs.readFileSync(pluginPath, 'utf-8')
          })
          log.info(` Loaded: ${pluginName}`)

          // 注册插件的每个工具
          if (pluginInfo.tools && Array.isArray(pluginInfo.tools)) {
            for (const tool of pluginInfo.tools) {
              this._registerPythonTool(pluginName, tool)
            }
          }
        }
      } catch (err) {
        log.error(` Failed to load ${file}:`, err.message)
      }
    }

    log.info(` Total Python plugins: ${this._pythonPlugins.size}`)
  }

  /**
   * 注册 Python 插件的工具
   * 工具名格式：插件名_工具名（如 stock_get_price）
   */
  _registerPythonTool(pluginName, tool) {
    if (!tool.name) return

    // 格式：pluginname_toolname
    const fullToolName = `${pluginName}_${tool.name}`

    try {
      this.registerTool({
        name: fullToolName,
        description: `[${pluginName}] ${tool.description || ''}`,
        pluginName: pluginName,
        inputSchema: this._parseToolParams(tool.params || {}),
        execute: async (args) => {
          return this._executePythonTool(pluginName, tool.name, args)
        }
      })
    } catch (err) {
      log.error(` Failed to register tool ${fullToolName}:`, err.message)
    }
  }

  /**
   * 解析工具参数 schema
   */
  _parseToolParams(params) {
    // 构建 JSON Schema 格式
    const properties = {}
    const required = []

    for (const [key, value] of Object.entries(params)) {
      let type = 'string'
      if (typeof value === 'boolean') type = 'boolean'
      else if (typeof value === 'number') type = 'number'
      else if (Array.isArray(value)) type = 'array'
      else if (typeof value === 'object') type = 'object'

      properties[key] = {
        type,
        description: ''
      }
      required.push(key)
    }

    const jsonSchema = {
      type: 'object',
      properties,
      required
    }

    // 转换为 Zod Schema 以兼容 AI SDK
    return jsonSchemaToZod(jsonSchema)
  }

  /**
   * 格式化参数描述（使用 zodSchemaToMarkdown）
   */
  _formatParams(params) {
    if (!params || Object.keys(params).length === 0) {
      return '无参数'
    }

    try {
      // 构建 JSON Schema 格式
      const properties = {}
      const required = []

      for (const [key, value] of Object.entries(params)) {
        let type = 'string'
        if (typeof value === 'boolean') type = 'boolean'
        else if (typeof value === 'number') type = 'number'
        else if (Array.isArray(value)) type = 'array'
        else if (typeof value === 'object' && value !== null) type = 'object'

        properties[key] = {
          type,
          description: ''
        }
        required.push(key)
      }

      const jsonSchema = {
        type: 'object',
        properties,
        required
      }

      // 转换为 Zod Schema
      const zodSchema = jsonSchemaToZod(jsonSchema)

      // 使用 zodSchemaToMarkdown 生成表格
      const table = zodSchemaToMarkdown(zodSchema)

      // 提取表格中的参数行，格式化为 "param: type" 形式
      const lines = table.split('\n')
      const paramLines = []

      for (const line of lines) {
        if (line.startsWith('| ') && !line.includes('字段') && !line.includes('---')) {
          const parts = line.split('|').map(s => s.trim())
          if (parts.length >= 3 && parts[1]) {
            const paramName = parts[1]
            const type = parts[2]
            paramLines.push(`${paramName}: ${type}`)
          }
        }
      }

      return paramLines.join(', ') || '无参数'
    } catch (err) {
      // fallback 到简单的参数名列表
      return Object.keys(params).join(', ') || '无参数'
    }
  }

  /**
   * 加载单个 Python 插件的元信息
   * 支持 PLUGIN 和 TOOLS 格式
   */
  _loadPythonPluginMeta(pluginPath) {
    const code = fs.readFileSync(pluginPath, 'utf-8')

    const pluginIdx = code.indexOf('PLUGIN')
    const toolsIdx = code.indexOf('TOOLS')

    if (pluginIdx === -1 && toolsIdx === -1) {
      console.warn(`[PythonPluginLoader] ${path.basename(pluginPath)}: no PLUGIN or TOOLS found`)
      return null
    }

    try {
      const info = {}

      // 解析 PLUGIN
      if (pluginIdx !== -1) {
        const pluginData = this._extractPythonDict(code, pluginIdx)
        if (pluginData && pluginData.name) {
          info.name = pluginData.name
          info.version = pluginData.version || '1.0.0'
          info.description = pluginData.description || ''
        }
      }

      // 解析 TOOLS
      if (toolsIdx !== -1) {
        const toolsData = this._extractPythonList(code, toolsIdx)
        if (toolsData && Array.isArray(toolsData)) {
          info.tools = toolsData
        }
      }

      if (!info.name || !info.tools) {
        console.warn(`[PythonPluginLoader] ${path.basename(pluginPath)}: invalid format - name: ${info.name}, tools: ${info.tools ? info.tools.length : 0}`)
        return null
      }

      return info
    } catch (err) {
      console.warn(`[PythonPluginLoader] Failed to parse ${path.basename(pluginPath)}:`, err.message)
      return null
    }
  }

  /**
   * 从指定位置提取 Python 字典
   */
  _extractPythonDict(code, startIdx) {
    const braceStart = code.indexOf('{', startIdx)
    if (braceStart === -1) return null

    let braceCount = 0
    let endIdx = -1
    for (let i = braceStart; i < code.length; i++) {
      if (code[i] === '{') braceCount++
      else if (code[i] === '}') {
        braceCount--
        if (braceCount === 0) {
          endIdx = i
          break
        }
      }
    }

    if (endIdx === -1) return null
    return this._parsePythonDict(code.substring(braceStart, endIdx + 1))
  }

  /**
   * 从指定位置提取 Python 列表
   */
  _extractPythonList(code, startIdx) {
    const bracketStart = code.indexOf('[', startIdx)
    if (bracketStart === -1) return null

    let bracketCount = 0
    let endIdx = -1
    for (let i = bracketStart; i < code.length; i++) {
      if (code[i] === '[') bracketCount++
      else if (code[i] === ']') {
        bracketCount--
        if (bracketCount === 0) {
          endIdx = i
          break
        }
      }
    }

    if (endIdx === -1) return null
    return this._parsePythonList(code.substring(bracketStart, endIdx + 1))
  }

  /**
   * 解析 Python 字典为 JS 对象
   */
  _parsePythonDict(str) {
    str = str.replace(/#.*$/gm, '').trim()
    if (!str || str === '{}') return {}

    // 直接尝试 JSON.parse（PLUGIN 字典是有效的 JSON 格式）
    try {
      return JSON.parse(str)
    } catch {
      // 如果失败，使用手动解析
    }

    const result = {}
    let i = 0
    let key = null
    let valueStart = -1
    let depth = 0
    let inString = false
    let stringChar = null
    let escaped = false

    while (i < str.length) {
      const char = str[i]

      if (escaped) {
        escaped = false
        i++
        continue
      }

      if (char === '\\' && inString) {
        escaped = true
        i++
        continue
      }

      if ((char === '"' || char === "'") && !inString) {
        inString = true
        stringChar = char
        i++
        continue
      }

      if (inString && char === stringChar) {
        inString = false
        i++
        continue
      }

      if (inString) {
        i++
        continue
      }

      if (char === '{' || char === '[') {
        if (depth === 0 && char === '{') {
          valueStart = i + 1
        }
        depth++
        i++
        continue
      }
      if (char === '}' || char === ']') {
        if (depth > 0) {
          depth--
          if (depth === 0 && char === '}') {
            if (key !== null && valueStart !== -1) {
              const valueStr = str.substring(valueStart, i).trim()
              if (valueStr) result[key] = this._parseValue(valueStr)
            }
          }
        }
        i++
        continue
      }
      if (depth > 0) {
        i++
        continue
      }

      if (char === ':') {
        key = str.substring(valueStart, i).trim().replace(/["']/g, '')
        valueStart = i + 1
        i++
        continue
      }

      if (char === ',') {
        if (key !== null && valueStart !== -1) {
          const valueStr = str.substring(valueStart, i).trim()
          if (valueStr) result[key] = this._parseValue(valueStr)
        }
        key = null
        valueStart = i + 1
        i++
        continue
      }

      i++
    }

    return result
  }

  /**
   * 解析 Python 列表为 JS 数组
   */
  _parsePythonList(str) {
    str = str.replace(/#.*$/gm, '').trim()
    if (!str || str === '[]') return []

    // 直接尝试 JSON.parse（TOOLS 列表是有效的 JSON 格式）
    try {
      return JSON.parse(str)
    } catch {
      // 如果失败，使用手动解析
    }

    const result = []
    let i = 0
    let itemStart = 1
    let depth = 0
    let inString = false
    let stringChar = null
    let escaped = false

    while (i < str.length) {
      const char = str[i]

      if (escaped) {
        escaped = false
        i++
        continue
      }

      if (char === '\\' && inString) {
        escaped = true
        i++
        continue
      }

      if ((char === '"' || char === "'") && !inString) {
        inString = true
        stringChar = char
        i++
        continue
      }

      if (inString && char === stringChar) {
        inString = false
        i++
        continue
      }

      if (inString) {
        i++
        continue
      }

      if (char === '{' || char === '[') {
        if (depth === 0) itemStart = i
        depth++
        i++
        continue
      }
      if (char === '}' || char === ']') {
        if (depth > 0) {
          depth--
          if (depth === 0) {
            const itemStr = str.substring(itemStart, i + 1).trim()
            if (itemStr && itemStr !== ',') {
              if (itemStr.startsWith('{')) {
                result.push(this._parsePythonDict(itemStr))
              } else {
                result.push(this._parseValue(itemStr))
              }
            }
            itemStart = i + 1
          }
        }
        i++
        continue
      }
      if (depth > 0) {
        i++
        continue
      }

      if (char === ',') {
        const itemStr = str.substring(itemStart, i).trim()
        if (itemStr) {
          if (itemStr.startsWith('{')) {
            result.push(this._parsePythonDict(itemStr))
          } else {
            result.push(this._parseValue(itemStr))
          }
        }
        itemStart = i + 1
      }

      i++
    }

    return result
  }

  /**
   * 解析单个值
   */
  _parseValue(str) {
    str = str.trim()
    if (!str) return null

    if (str.startsWith('{')) {
      return this._parsePythonDict(str)
    }

    if (str.startsWith('"') || str.startsWith("'")) {
      return str.slice(1, -1)
    }

    if (str === 'True') return true
    if (str === 'False') return false
    if (str === 'None') return null

    if (!isNaN(str)) return Number(str)

    return str
  }

  /**
   * 执行 Python 插件工具
   */
  async _executePythonTool(pluginName, toolName, params) {
    const plugin = this._pythonPlugins.get(pluginName)
    if (!plugin) {
      return { success: false, error: `Plugin '${pluginName}' not found` }
    }

    // 构建执行代码 - 使用 base64 避免转义问题
    const pluginDir = path.dirname(plugin.path)
    const codeBase64 = Buffer.from(plugin.code, 'utf-8').toString('base64')

    const execCode = `
import sys
import base64
sys.path.insert(0, r'${pluginDir}')

# 加载插件代码
plugin_code = base64.b64decode('${codeBase64}').decode('utf-8')
exec(compile(plugin_code, '${pluginName}.py', 'exec'))

# 执行工具
result = execute_tool('${toolName}', ${JSON.stringify(params)})
print(result)
`

    try {
      // 通过 python-execute 工具执行
      const pythonExe = this._framework.toolRegistry._tools.get('python-execute')
      if (!pythonExe) {
        return { success: false, error: 'python-execute tool not found. Please install python-executor-plugin.' }
      }

      const pythonResult = await pythonExe.execute({ code: execCode })

      if (pythonResult.success) {
        try {
          // 尝试解析 JSON 结果
          const parsed = JSON.parse(pythonResult.output)
          return parsed
        } catch {
          return { success: true, output: pythonResult.output }
        }
      } else {
        return { success: false, error: pythonResult.error }
      }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  /**
   * 获取所有已加载的 Python 插件
   */
  getPythonPlugins() {
    return Array.from(this._pythonPlugins.values())
  }

  /**
   * 获取 Python 插件信息
   */
  getPythonPlugin(name) {
    return this._pythonPlugins.get(name)
  }
}

module.exports = PythonPluginLoader
