#!/usr/bin/env ruby

require 'time'

def format_relative_time(seconds)
  return "刚刚" if seconds.abs < 60

  is_past = seconds > 0
  suffix = is_past ? "前" : "后"
  abs_seconds = seconds.abs.to_i

  if abs_seconds >= 365 * 24 * 60 * 60
    years = abs_seconds / (365 * 24 * 60 * 60)
    "#{years}年#{suffix}"
  elsif abs_seconds >= 30 * 24 * 60 * 60
    months = abs_seconds / (30 * 24 * 60 * 60)
    "#{months}个月#{suffix}"
  elsif abs_seconds >= 7 * 24 * 60 * 60
    weeks = abs_seconds / (7 * 24 * 60 * 60)
    "#{weeks}周#{suffix}"
  elsif abs_seconds >= 24 * 60 * 60
    days = abs_seconds / (24 * 60 * 60)
    "#{days}天#{suffix}"
  elsif abs_seconds >= 60 * 60
    hours = abs_seconds / (60 * 60)
    "#{hours}小时#{suffix}"
  elsif abs_seconds >= 60
    minutes = abs_seconds / 60
    "#{minutes}分钟#{suffix}"
  else
    "#{abs_seconds}秒#{suffix}"
  end
end

def process_timestamp(input)
  ts = input.to_i

  # 智能识别：如果是 13 位数字，认为是毫秒；如果是 10 位，认为是秒
  # 如果数字范围在合理的时间戳范围内，也可以判断
  if ts.to_s.length == 13
    time = Time.at(ts / 1000.0)
  elsif ts.to_s.length == 10
    time = Time.at(ts)
  elsif ts > 1_000_000_000_000
    # 超过这个值的可能是毫秒级时间戳（约 2001 年之后）
    time = Time.at(ts / 1000.0)
  else
    time = Time.at(ts)
  end

  now = Time.now
  relative = format_relative_time(now - time)

  puts "时间:    #{time.strftime('%Y-%m-%d %H:%M:%S')}"
  puts "相对时间: #{relative}"
end

def process_iso8601(input)
  time = Time.parse(input)
  now = Time.now
  relative = format_relative_time(now - time)
  ms_timestamp = (time.to_f * 1000).to_i

  puts "本地时间:   #{time.strftime('%Y-%m-%d %H:%M:%S')}"
  puts "时区:      #{time.strftime('%z')}"
  puts "UTC 时间:  #{time.getutc.strftime('%Y-%m-%d %H:%M:%S')}"
  puts "相对时间:  #{relative}"
  puts "毫秒时间戳: #{ms_timestamp}"
end

def main
  if ARGV.empty?
    puts "用法: ,timestamp <时间戳|ISO8601时间>"
    puts ""
    puts "示例:"
    puts "  ,timestamp 1717584000"
    puts "  ,timestamp 1717584000000"
    puts "  ,timestamp 2024-06-05T12:00:00Z"
    puts "  ,timestamp 2024-06-05T12:00:00+08:00"
    exit 1
  end

  input = ARGV[0].strip

  if input =~ /^\d+$/
    process_timestamp(input)
  else
    process_iso8601(input)
  end
end

main
