extends Node

var start_time: int = 0
var log_file_path: String
var comments: Array = []
var session_start_iso: String = ""

func _ready():
	start_time = Time.get_ticks_msec()
	session_start_iso = _get_iso_timestamp()

	var datetime = Time.get_datetime_dict_from_system()
	var timestamp_fname = "chat_log_%04d-%02d-%02d_%02d-%02d-%02d.json" % [
		datetime.year, datetime.month, datetime.day,
		datetime.hour, datetime.minute, datetime.second
	]

	var base_path = SystemManager.get_program_path().path_join("chat_logs")
	DirAccess.make_dir_recursive_absolute(base_path)
	log_file_path = base_path.path_join(timestamp_fname)

	_save_json()

func log_message(chat_msg: TwitchChatMessage):
	var elapsed_ms = Time.get_ticks_msec() - start_time
	var offset_seconds: float = elapsed_ms / 1000.0

	var td_emoticons = []
	var td_fragments = []
	var full_body_text = ""
	var current_pos = 0

	for fragment in chat_msg.message.fragments:
		var frag_text = fragment.text
		var frag_data = { "text": frag_text, "emoticon": null }

		# FragmentType.emote is 2
		if fragment.type == 2 and fragment.emote != null:
			var e_id = str(fragment.emote.id)
			var start_index = current_pos
			var end_index = current_pos + frag_text.length() - 1

			td_emoticons.append({
				"_id": e_id,
				"begin": start_index,
				"end": end_index
			})

			frag_data["emoticon"] = { "emoticon_id": e_id }

		td_fragments.append(frag_data)
		full_body_text += frag_text
		current_pos += frag_text.length()

	var comment_entry = {
		"_id": chat_msg.message_id,
		"created_at": _get_iso_timestamp(),
		"channel_id": chat_msg.broadcaster_user_id,
		"content_offset_seconds": offset_seconds,
		"commenter": {
			"display_name": chat_msg.chatter_user_name,
			"name": chat_msg.chatter_user_login,
			"_id": chat_msg.chatter_user_id
		},
		"message": {
			"body": full_body_text,
			"fragments": td_fragments,
			"user_color": chat_msg.get_color("#FFFFFF"),
			"user_badges": [],
			"emoticons": td_emoticons
		}
	}

	comments.append(comment_entry)
	_save_json()

func _save_json():
	var elapsed_ms = Time.get_ticks_msec() - start_time
	var total_s = int(elapsed_ms / 1000)

	var duration_str = "%dh%dm%ds" % [total_s / 3600, (total_s / 60) % 60, total_s % 60]

	var full_data = {
		"FileInfo": { "Version": {"Major": 1, "Minor": 56, "Patch": 2} },
		"streamer": {ConfigManager.get_setting("client_auth", "broadcaster_username"): "LiveStream", "id": 0},
		"video": {
			"id": "0",
			"title": "Live Log",
			"created_at": session_start_iso,
			"duration": duration_str,
			"length": total_s,
			"viewable": "public"
		},
		"comments": comments
	}

	var file = FileAccess.open(log_file_path, FileAccess.WRITE)
	if file:
		file.store_string(JSON.stringify(full_data))
		file.close()

func _get_iso_timestamp() -> String:
	var dict = Time.get_datetime_dict_from_system()
	return "%04d-%02d-%02dT%02d:%02d:%02dZ" % [
		dict.year, dict.month, dict.day,
		dict.hour, dict.minute, dict.second
	]
