require "json"
require "time"
require "fileutils"
require "cgi"

ROOT = File.expand_path(__dir__)
DATA_DIR = File.join(ROOT, "data")
DATA_FILE = File.join(DATA_DIR, "incidents.json")
EXPORT_FILE = File.join(DATA_DIR, "latest_report.md")
DASHBOARD_FILE = File.join(DATA_DIR, "incident_dashboard.html")

def save_data(data)
  FileUtils.mkdir_p(DATA_DIR)
  File.write(DATA_FILE, JSON.pretty_generate(data))
end

def seed_demo_data
  data = [
    {
      "id" => "INC-2001",
      "title" => "Laptop user lambat saat booting",
      "severity" => "medium",
      "owner" => "Doni",
      "status" => "open",
      "created_at" => Time.now.iso8601,
      "notes" => "Perlu cek startup apps"
    },
    {
      "id" => "INC-2002",
      "title" => "Access point restart sendiri",
      "severity" => "high",
      "owner" => "Lina",
      "status" => "investigating",
      "created_at" => Time.now.iso8601,
      "notes" => "Diduga adaptor daya longgar"
    }
  ]
  save_data(data)
  data
end

def ensure_files
  FileUtils.mkdir_p(DATA_DIR)
  return if File.exist?(DATA_FILE)
  seed_demo_data
end

def load_data
  ensure_files
  JSON.parse(File.read(DATA_FILE))
end

def next_id(data)
  max = data.map { |x| x["id"].to_s.split("-").last.to_i }.max || 2000
  "INC-#{max + 1}"
end

def metrics(data)
  {
    total: data.length,
    open: data.count { |x| x["status"] == "open" },
    investigating: data.count { |x| x["status"] == "investigating" },
    resolved: data.count { |x| x["status"] == "resolved" },
    high: data.count { |x| x["severity"] == "high" }
  }
end

def list_incidents(data)
  puts "\n=== DAFTAR INSIDEN ==="
  data.each do |item|
    puts "#{item["id"]} | #{item["title"]} | #{item["severity"]} | #{item["status"]} | #{item["owner"]}"
  end
end

def create_incident(data)
  print "Judul: "
  title = STDIN.gets&.strip.to_s
  print "Severity (low/medium/high): "
  severity = STDIN.gets&.strip.to_s
  print "PIC: "
  owner = STDIN.gets&.strip.to_s
  print "Catatan awal: "
  notes = STDIN.gets&.strip.to_s

  data << {
    "id" => next_id(data),
    "title" => title.empty? ? "Insiden baru" : title,
    "severity" => severity.empty? ? "medium" : severity,
    "owner" => owner.empty? ? "Belum ditetapkan" : owner,
    "status" => "open",
    "created_at" => Time.now.iso8601,
    "notes" => notes
  }
  save_data(data)
  puts "Insiden berhasil dibuat."
end

def resolve_incident(data)
  print "Masukkan ID insiden: "
  id = STDIN.gets&.strip.to_s
  item = data.find { |x| x["id"] == id }
  if item.nil?
    puts "Insiden tidak ditemukan."
    return
  end
  item["status"] = "resolved"
  item["resolved_at"] = Time.now.iso8601
  save_data(data)
  puts "Insiden ditandai selesai."
end

def export_report(data)
  lines = []
  lines << "# Laporan Insiden"
  lines << ""
  lines << "Dibuat: #{Time.now.strftime("%Y-%m-%d %H:%M:%S")}"
  lines << ""
  data.each do |item|
    lines << "- #{item["id"]} | #{item["title"]} | #{item["severity"]} | #{item["status"]} | #{item["owner"]}"
  end
  File.write(EXPORT_FILE, lines.join("\n"))
  EXPORT_FILE
end

def build_dashboard(data)
  stats = metrics(data)
  rows = data.map do |item|
    <<~HTML
      <tr>
        <td>#{CGI.escapeHTML(item["id"].to_s)}</td>
        <td>#{CGI.escapeHTML(item["title"].to_s)}</td>
        <td>#{CGI.escapeHTML(item["severity"].to_s)}</td>
        <td>#{CGI.escapeHTML(item["status"].to_s)}</td>
        <td>#{CGI.escapeHTML(item["owner"].to_s)}</td>
        <td>#{CGI.escapeHTML(item["notes"].to_s)}</td>
      </tr>
    HTML
  end.join("\n")

  html = <<~HTML
    <!doctype html>
    <html lang="id">
    <head>
      <meta charset="utf-8">
      <title>Incident Report Builder Ruby</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <style>
        body { font-family: Segoe UI, Arial, sans-serif; margin: 0; background: #f8fafc; color: #0f172a; }
        header { padding: 22px 28px; background: linear-gradient(135deg, #1e293b, #2563eb); color: white; }
        main { padding: 22px 28px; display: grid; gap: 18px; }
        .metrics { display: grid; gap: 14px; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); }
        .card { background: white; border: 1px solid #e2e8f0; border-radius: 16px; padding: 16px; box-shadow: 0 12px 24px rgba(15, 23, 42, 0.06); }
        .label { color: #475569; font-size: 13px; margin-bottom: 6px; }
        .value { font-size: 28px; font-weight: 700; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 10px 8px; text-align: left; border-bottom: 1px solid #e2e8f0; vertical-align: top; }
        th { color: #475569; font-weight: 600; }
        .note { color: #475569; font-size: 13px; }
      </style>
    </head>
    <body>
      <header>
        <h1>Incident Report Builder Ruby</h1>
        <p>Dashboard HTML untuk menjelaskan ringkasan insiden secara cepat saat presentasi.</p>
      </header>
      <main>
        <section class="metrics">
          <div class="card"><div class="label">Total Insiden</div><div class="value">#{stats[:total]}</div></div>
          <div class="card"><div class="label">Open</div><div class="value">#{stats[:open]}</div></div>
          <div class="card"><div class="label">Investigating</div><div class="value">#{stats[:investigating]}</div></div>
          <div class="card"><div class="label">Resolved</div><div class="value">#{stats[:resolved]}</div></div>
          <div class="card"><div class="label">Severity High</div><div class="value">#{stats[:high]}</div></div>
        </section>
        <section class="card">
          <h2>Daftar Insiden</h2>
          <table>
            <thead><tr><th>ID</th><th>Judul</th><th>Severity</th><th>Status</th><th>PIC</th><th>Catatan</th></tr></thead>
            <tbody>#{rows}</tbody>
          </table>
        </section>
        <p class="note">Tip presentasi: jelaskan severity, status penanganan, dan contoh tindakan PIC pada tiap insiden.</p>
      </main>
    </body>
    </html>
  HTML

  File.write(DASHBOARD_FILE, html)
  DASHBOARD_FILE
end

def smoke_test
  data = load_data
  puts JSON.pretty_generate({
    app: "incident-report-builder-ruby",
    incidents: data.length,
    metrics: metrics(data),
    dashboard_file: File.basename(DASHBOARD_FILE)
  })
end

if ARGV.include?("--smoke-test")
  smoke_test
  exit 0
end

if ARGV.include?("--dashboard")
  data = load_data
  puts build_dashboard(data)
  exit 0
end

if ARGV.include?("--seed-demo")
  data = seed_demo_data
  puts JSON.pretty_generate({ app: "incident-report-builder-ruby", seeded: data.length })
  exit 0
end

ensure_files
data = load_data

loop do
  puts "\n=== Incident Report Builder Ruby ==="
  puts "1. Lihat daftar insiden"
  puts "2. Tambah insiden"
  puts "3. Selesaikan insiden"
  puts "4. Ekspor laporan Markdown"
  puts "5. Seed demo data"
  puts "6. Bangun dashboard HTML"
  puts "0. Keluar"
  print "Pilih menu: "
  choice = STDIN.gets&.strip.to_s

  case choice
  when "1"
    list_incidents(data)
  when "2"
    create_incident(data)
    data = load_data
  when "3"
    resolve_incident(data)
    data = load_data
  when "4"
    file = export_report(data)
    puts "Laporan disimpan di #{file}"
  when "5"
    data = seed_demo_data
    puts "Seed data berhasil."
  when "6"
    file = build_dashboard(data)
    puts "Dashboard dibuat di #{file}"
  when "0"
    puts "Selesai."
    break
  else
    puts "Menu tidak valid."
  end
end
