#!/usr/bin/env bash

query="$*"
shift

set -e pipefile

if [[ -z "$query" ]]; then
	echo "No query provided"
	exit 1
fi

root=$(git rev-parse --show-toplevel)

source "$root/.env"

# login
if [[ -e /tmp/igdb-login.json ]]; then
	token=$(jq -r '.access_token' /tmp/igdb-login.json)
else
	login_url="https://id.twitch.tv/oauth2/token?client_id=$IGDB_CLIENT_ID&client_secret=$IGDB_CLIENT_SECRET&grant_type=client_credentials"
	token=$(curl -s -X POST "$login_url" | tee /tmp/igdb-login.json | jq -r '.access_token')
fi

if [[ "$token" == "null" ]]; then
	echo "Couldn't fetch token"
	exit 1
fi

# Select entry
fields="name, slug, summary, url, parent_game.name, franchises.name, franchises.slug, genres.name, platforms.name, first_release_date, platforms.name, involved_companies.company.name"
limit=100

preview=".[{n}] | .first_release_date = (.first_release_date // 0 | strflocaltime(\"%Y-%m-%d\")) | del(.id, .slug, .summary) | walk(if type == \"array\" then map((.name // .company.name)?) else . end )"

line=$(curl -s 'https://api.igdb.com/v4/games' \
	-H "Client-ID: $IGDB_CLIENT_ID" \
	-H "Authorization: Bearer $token" \
	-H 'Accept: application/json' \
	-d "search \"$query\"; fields $fields; limit $limit;" | tee /tmp/igdb-query.json |
	jq -r '.[].name' |
	fzf --preview "jq --sort-keys --color-output '$preview' /tmp/igdb-query.json" --bind "ctrl-o:execute-silent(jq -r '.[{n}].url' /tmp/igdb-query.json | xargs xdg-open)" --bind 'enter:become(echo {n})')

if [[ -z $line ]]; then
	echo "No entry selected..."
	exit
fi

filter="{ title: .name, alias: .name, release: .first_release_date | strflocaltime(\"%Y-%m-%d\"), franchises: (if .franchises then .franchises | map(.name) else [\"None\"] end), developers: (.involved_companies | map(.company.name) | unique), genres: (.genres | map(.name)), url, status: \"Backlog\", times_played: 0, registered_hours: 0, has_content: false, date_added: now | strftime(\"%Y-%m-%d\")}"

# Create frontmatter
slug=$(jq --compact-output -r ".[$line] | .slug" /tmp/igdb-query.json)
entry=$(jq --compact-output -r ".[$line] | $filter" /tmp/igdb-query.json)

# TODO: figure out how to pass $entry to python
frontmatter=$(python -c 'import sys, yaml, json; print(yaml.dump(json.loads(sys.stdin.read())))' <<<"$entry")
frontmatter="---\n$frontmatter\n---"
frontmatter="$frontmatter\n\n# $(jq -r ".[$line] | .name" /tmp/igdb-query.json)"
frontmatter="$frontmatter\n\n## Brief"
frontmatter="$frontmatter\n\n> $(jq -r ".[$line] | .summary" /tmp/igdb-query.json)"
frontmatter="$frontmatter\n\n## Thoughts"

file="$root/games/$slug.md"

if [[ -e "$file" ]]; then
	echo "File exist, here is the frontmatter to update it:"
	echo
	echo -e "$frontmatter"
else
	echo -e "$frontmatter" >"$file"
	echo "file created at: $file"
fi
