#!/bin/zsh

help=(
	at.zsh d handle
	at.zsh u at-uri
	at.zsh c at-uri -r
	at.zsh docs
)
host=(
	bsky.social
	public.api.bsky.app
	plc.directory
)
lexicon=(
 com.atproto.repo.describeRepo
 com.atproto.repo.getRecord
 com.atproto.repo.listRecords
 com.atproto.identity.resolveHandle
)

function at-env(){
	host=bsky.social
	at_uri=at://did:plc:4hqjfn7m6n5hno3doamuhgef/ai.syui.game.user/syui
	docs_uri=https://docs.bsky.app/docs/api
	handle=yui.syui.ai
	did=`echo $at_uri|cut -d / -f 3`
	collection=`echo $at_uri|cut -d / -f 4`
	rkey=`echo $at_uri|cut -d / -f 5`
}

function at-uri-search(){
	if [ -n "$1" ];then
		at_uri=$1
	fi
	req=/xrpc/com.atproto.repo.getRecord
	url=https://${host}${req}
	did=`echo $at_uri|cut -d / -f 3`
	collection=`echo $at_uri|cut -d / -f 4`
	rkey=`echo $at_uri|cut -d / -f 5`
	curl -sL "$url?repo=$did&collection=$collection&rkey=$rkey"|jq .
}

function at-did-search(){
	if [ -n "$1" ];then
		handle=$1
	fi
	req=/xrpc/com.atproto.repo.describeRepo
	url=https://${host}${req}
	curl -sL "$url?repo=$handle"|jq .
}

function at-collection-search(){
	reverse=false
	if [ -n "$1" ];then
		at_uri=$1
	fi
	if [ "$2" = "-r" ];then
		reverse=true
	fi
	req=/xrpc/com.atproto.repo.listRecords
	url=https://${host}${req}
	did=`echo $at_uri|cut -d / -f 3`
	collection=`echo $at_uri|cut -d / -f 4`
	curl -sL "$url?repo=$did&collection=$collection&reverse=$reverse"|jq .
}


function at-docs(){
for i in $lexicon; do
	req=`echo $i|tr '.' '-'|sed 's/[A-Z]/-&/g'|tr '[A-Z]' '[a-z]'`
	url=$docs_uri/$req
	echo $url
done
}

at-env
case $1 in
	uri|u)
		at-uri-search $2
		;;
	did|d)
		at-did-search $2
		;;
	collection|c)
		at-collection-search $2 $3
		;;
	at-docs|docs)
		at-docs
		;;
	*)
		echo "${help[@]}"
		echo "${host[@]}"
		echo "${lexicon[@]}"
		;;
esac