# frozen_string_literal: true

# 报告相关路由
module ReportRoutes
  def self.registered(app)
    # 报告页面
    app.get '/tasks/:id/report' do
      @task = LocalTask[params[:id]]
      halt 404, '任务不存在' unless @task
      @active_page = 'tasks'
      @task_id = @task.id
      erb :task_report, layout: true
    end

    # 获取报告数据 API
    app.get '/api/tasks/:id/report' do
      content_type :json
      task = LocalTask[params[:id]]
      halt 404, { error: '任务不存在' }.to_json unless task

      begin
        report = ReportGenerator.instance.generate_report(task)
        report.to_json
      rescue StandardError => e
        halt 500, { error: "生成报告失败: #{e.message}" }.to_json
      end
    end

    # 导出报告
    app.get '/api/tasks/:id/report/export' do
      task = LocalTask[params[:id]]
      halt(404, { error: '任务不存在' }.to_json) unless task

      format = params[:format] || 'json'

      begin
        report = ReportGenerator.instance.generate_report(task)

        case format
        when 'json'
          content_type 'application/json'
          headers['Content-Disposition'] = "attachment; filename=\"task_report_#{task.id}.json\""
          JSON.pretty_generate(report)
        when 'html'
          content_type 'text/html; charset=utf-8'
          headers['Content-Disposition'] = "attachment; filename=\"task_report_#{task.id}.html\""
          ReportHtmlGenerator.generate(task, report)
        else
          halt(400, { error: '不支持的导出格式' }.to_json)
        end
      rescue StandardError => e
        puts "[Report Export Error] #{e.class}: #{e.message}"
        puts e.backtrace.join("\n")
        halt(500, { error: "导出失败: #{e.message}" }.to_json)
      end
    end
  end
end

# HTML 报告生成器
module ReportHtmlGenerator
  def self.generate(task, report)
    data = JSON.parse(report.to_json)

    task_data = data['task'] || {}
    statistics = data['statistics'] || {}
    devices = data['devices'] || []
    errors = data['errors'] || []

    task_status = task_data['status']
    task_status_text = task_data['status_text']
    started_at = task_data['started_at']
    completed_at = task_data['completed_at']
    duration = task_data['duration']

    <<~HTML
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>任务报告 - #{escape_html(task.name)}</title>
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; background: #f5f7fa; padding: 24px; }
    .container { max-width: 1200px; margin: 0 auto; background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 32px; }
    h1 { font-size: 24px; color: #303133; margin-bottom: 8px; }
    h2 { font-size: 18px; color: #303133; margin: 24px 0 16px; padding-bottom: 8px; border-bottom: 2px solid #409eff; }
    .meta { color: #909399; font-size: 14px; margin-bottom: 24px; }
    .tag { display: inline-block; padding: 4px 12px; border-radius: 4px; font-size: 14px; margin-right: 8px; }
    .tag-success { background: #f0f9eb; color: #67c23a; }
    .tag-warning { background: #fdf6ec; color: #e6a23c; }
    .tag-danger { background: #fef0f0; color: #f56c6c; }
    .tag-info { background: #ecf5ff; color: #409eff; }
    .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 16px; margin-bottom: 24px; }
    .stat-card { background: #f5f7fa; padding: 16px; border-radius: 6px; text-align: center; }
    .stat-value { font-size: 28px; font-weight: bold; color: #303133; }
    .stat-label { font-size: 12px; color: #909399; margin-top: 4px; }
    .device-card { border: 1px solid #ebeef5; border-radius: 8px; margin-bottom: 16px; overflow: hidden; }
    .device-header { padding: 16px; background: #f5f7fa; display: flex; justify-content: space-between; align-items: center; }
    .device-title { font-weight: 600; color: #303133; }
    .device-meta { color: #909399; font-size: 14px; }
    table { width: 100%; border-collapse: collapse; }
    th, td { padding: 12px 16px; text-align: left; border-bottom: 1px solid #ebeef5; }
    th { background: #fafafa; font-weight: 600; color: #606266; font-size: 14px; }
    td { color: #606266; font-size: 14px; }
    .error-section { background: #fef0f0; border: 1px solid #fde2e2; border-radius: 8px; padding: 16px; margin-top: 24px; }
    .error-title { color: #f56c6c; font-weight: 600; margin-bottom: 12px; }
    .error-item { padding: 8px 0; border-bottom: 1px solid #fde2e2; }
    .error-item:last-child { border-bottom: none; }
  </style>
</head>
<body>
  <div class="container">
    <h1>任务报告：#{escape_html(task.name)}</h1>
    <div class="meta">
      <span class="tag #{task_status == 'completed' ? 'tag-success' : task_status == 'failed' ? 'tag-danger' : 'tag-info'}">#{escape_html(task_status_text)}</span>
      开始时间：#{started_at ? Time.parse(started_at).strftime('%Y-%m-%d %H:%M:%S') : '-'} |
      完成时间：#{completed_at ? Time.parse(completed_at).strftime('%Y-%m-%d %H:%M:%S') : '-'} |
      耗时：#{escape_html(duration || '-')}
    </div>

    <h2>概览统计</h2>
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-value">#{statistics['total_devices']}</div>
        <div class="stat-label">总设备数</div>
      </div>
      <div class="stat-card">
        <div class="stat-value" style="color: #67c23a">#{statistics['all_success_devices']}</div>
        <div class="stat-label">全部成功</div>
      </div>
      <div class="stat-card">
        <div class="stat-value" style="color: #e6a23c">#{statistics['partial_success_devices']}</div>
        <div class="stat-label">部分成功</div>
      </div>
      <div class="stat-card">
        <div class="stat-value" style="color: #f56c6c">#{statistics['all_failed_devices']}</div>
        <div class="stat-label">全部失败</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">#{statistics['total_scripts']}</div>
        <div class="stat-label">总脚本数</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">#{escape_html(statistics['script_success_rate'] || '0%')}</div>
        <div class="stat-label">脚本成功率</div>
      </div>
    </div>

    <h2>执行详情</h2>
    #{devices.map { |device| generate_device_html(device) }.join}

    #{(errors && !errors.empty?) ? generate_errors_html(errors) : ''}
  </div>
</body>
</html>
HTML
  end

  def self.generate_device_html(device)
    status = device['status']
    status_color = case status
                   when 'completed' then '#67c23a'
                   when 'partial' then '#e6a23c'
                   when 'failed' then '#f56c6c'
                   else '#909399'
                   end
    status_icon = case status
                  when 'completed' then '✓'
                  when 'partial' then '!'
                  when 'failed' then '✗'
                  else '○'
                  end

    name = device['name']
    device_ip = device['device_ip']
    device_model = device['device_model']
    scripts_success = device['scripts_success']
    scripts_count = device['scripts_count']
    duration = device['duration']
    status_text = device['status_text']
    scripts = device['scripts'] || []

    <<~HTML
    <div class="device-card">
      <div class="device-header">
        <div>
          <span class="device-title">[#{status_icon}] #{escape_html(name)} (#{escape_html(device_ip)}) - #{escape_html(device_model || '未知型号')}</span>
          <span class="device-meta" style="margin-left: 12px;">[#{scripts_success}/#{scripts_count} 成功]</span>
          <span class="device-meta" style="margin-left: 12px;">耗时: #{escape_html(duration || '-')}</span>
        </div>
        <span style="color: #{status_color}; font-weight: 500;">#{escape_html(status_text)}</span>
      </div>
      <table>
        <thead>
          <tr>
            <th style="width: 200px;">脚本名称</th>
            <th style="width: 100px;">状态</th>
            <th style="width: 100px;">耗时</th>
            <th>结论摘要</th>
          </tr>
        </thead>
        <tbody>
          #{scripts.map { |script| generate_script_html(script) }.join}
        </tbody>
      </table>
    </div>
    HTML
  end

  def self.generate_script_html(script)
    status = script['status']
    status_text = case status
                  when 'completed' then '成功'
                  when 'failed' then '失败'
                  when 'running' then '执行中'
                  else '待执行'
                  end

    name = script['name']
    duration = script['duration']
    conclusion = script['conclusion']
    error = script['error']

    <<~HTML
    <tr>
      <td>#{escape_html(name)}</td>
      <td>#{escape_html(status_text)}</td>
      <td>#{escape_html(duration || '-')}</td>
      <td>#{escape_html(conclusion || error || '-')}</td>
    </tr>
    HTML
  end

  def self.generate_errors_html(errors)
    <<~HTML
    <div class="error-section">
      <div class="error-title">错误汇总</div>
      #{errors.map { |error| generate_error_item_html(error) }.join}
    </div>
    HTML
  end

  def self.generate_error_item_html(error)
    error_msg = error['error']
    count = error['count']
    affected_devices = error['affected_devices'] || []
    affected = affected_devices.map { |d| "#{d['device_name']} (#{d['device_ip']}) - #{d['script_name']}" }.join('、')

    <<~HTML
    <div class="error-item">
      <div style="color: #f56c6c; font-weight: 500;">#{escape_html(error_msg)}</div>
      <div style="color: #909399; font-size: 13px; margin-top: 4px;">影响 #{count} 项：#{escape_html(affected)}</div>
    </div>
    HTML
  end

  def self.escape_html(str)
    return '' if str.nil?
    str.to_s.gsub(/[&<>"']/, {
      '&' => '&amp;',
      '<' => '&lt;',
      '>' => '&gt;',
      '"' => '&quot;',
      "'" => '&#39;'
    })
  end
end
