-- Helper for LÖVE pre-v12.
-- Download a thread before running the LÖVE app on the results.

json = require 'json'
https = require 'ssl.https'

-- Construct an URL to query the Mastodon API.
-- I have no idea if ActivityPub carves out the id space between federating
-- hosts (how would it even do that?!) so I'm going to remember two things for
-- each Mastodon link: a host and an id. The host includes the protocol.
function url_from_ml(ml)
  return ('%s/api/v1/statuses/%d'):format(ml.host, ml.id)
end

-- We can parse the Mastodon link from the following formats:
--  https://merveilles.town/users/bd/statuses/109791902220118251
--  https://merveilles.town/@bd/109791902220118251
function ml_from_url(url)
  local host, user, id = url:match('^([^/]*://[^/]*)/@([^/]*)/(%d*)$')
  if host then return {host=host, user=user, id=id} end
  local host, user, id = url:match('^([^/]*://[^/]*)/users/([^/]*)/statuses/(%d*)$')
  if host then return {host=host, user=user, id=id} end
end

-- Given a mastodon link, return all information about it.
function get(ml)
  local url = url_from_ml(ml)
  print('getting '..url)
  local response, code, response_headers, status = https.request(url)
--?   print(response)
  local result = json.decode(response)
  local response, code, response_headers, status = https.request(url..'/context')
--?   print(response)
  local rels = json.decode(response)
  result.host = ml.host
  result.user = ml.user
  result.id = ml.id
  result.ancestors = rels.ancestors
  result.descendants = rels.descendants
  return result
end

if #arg == 0 then
  io.stderr:write('provide a Mastodon URL on the command line\n')
  os.exit(1)
end

local initial_ml = ml_from_url(arg[1])
local result = get(initial_ml)
if result.ancestors and #result.ancestors > 0 then
  result = get(ml_from_url(result.ancestors[1].url))
end

local filename = os.tmpname()
local f = io.open(filename, 'w')
f:write(json.encode(result))
f:close()
print(filename)

os.execute('love . '..filename..' '..initial_ml.id)
os.remove(filename)