/*
 * What the server says, as structs: posts (one struct per post, looked
 * up by its address, so every list shows the same one), the entries of
 * feeds, threads and notifications, people; and the other way, a new
 * post's record with its links, mentions and tags marked.
 */
#include <string.h>
#include <time.h>
#include "sky.h"

/* Small things */

void sky_query(GString *call, const char *key, const char *value) {
	char *escaped = g_uri_escape_string(value, NULL, FALSE);
	g_string_append_printf(call, "%c%s=%s", strchr(call->str, '?') ? '&' : '?',
		key, escaped);
	g_free(escaped);
}

void sky_json_str(GString *out, const char *text) {
	g_string_append_c(out, '"');
	for (const unsigned char *p = (const unsigned char *)text; *p; p++) {
		if (*p == '"' || *p == '\\') {
			g_string_append_c(out, '\\');
			g_string_append_c(out, (char)*p);
		} else if (*p == '\n') {
			g_string_append(out, "\\n");
		} else if (*p < 0x20) {
			g_string_append_printf(out, "\\u%04x", *p);
		} else {
			g_string_append_c(out, (char)*p);
		}
	}
	g_string_append_c(out, '"');
}

char *sky_now_iso(void) {
	GDateTime *now = g_date_time_new_now_utc();
	char *text = g_strdup_printf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
		g_date_time_get_year(now), g_date_time_get_month(now),
		g_date_time_get_day_of_month(now), g_date_time_get_hour(now),
		g_date_time_get_minute(now), g_date_time_get_second(now),
		g_date_time_get_microsecond(now) / 1000);
	g_date_time_unref(now);
	return text;
}

int64_t sky_parse_time(const char *iso) {
	if (iso == NULL || iso[0] == '\0') {
		return 0;
	}
	GDateTime *t = g_date_time_new_from_iso8601(iso, NULL);
	if (t == NULL) {
		return 0;
	}
	int64_t unix_s = g_date_time_to_unix(t);
	g_date_time_unref(t);
	return unix_s;
}

char *sky_age(int64_t date) {
	if (date <= 0) {
		return g_strdup("");
	}
	int64_t now = g_get_real_time() / G_USEC_PER_SEC;
	int64_t ago = now - date;
	if (ago < 60) {
		return g_strdup("now");
	}
	if (ago < 3600) {
		return g_strdup_printf("%dm", (int)(ago / 60));
	}
	if (ago < 86400) {
		return g_strdup_printf("%dh", (int)(ago / 3600));
	}
	if (ago < 7 * 86400) {
		return g_strdup_printf("%dd", (int)(ago / 86400));
	}
	GDateTime *t = g_date_time_new_from_unix_local(date);
	GDateTime *today = g_date_time_new_now_local();
	char *text = g_date_time_format(t, g_date_time_get_year(t) ==
		g_date_time_get_year(today) ? "%-e %b" : "%-e %b %Y");
	g_date_time_unref(t);
	g_date_time_unref(today);
	return text;
}

char *sky_rkey(const char *uri) {
	const char *slash = uri ? strrchr(uri, '/') : NULL;
	return g_strdup(slash ? slash + 1 : "");
}

char *sky_avatar_small(const char *url) {
	if (url == NULL) {
		return NULL;
	}
	const char *at = strstr(url, "/img/avatar/");
	if (at == NULL) {
		return g_strdup(url);
	}
	return g_strdup_printf("%.*s/img/avatar_thumbnail/%s", (int)(at - url), url,
		at + strlen("/img/avatar/"));
}

/* Text from the server: valid UTF-8, or NULL for none */
static char *text_of(const struct json *json) {
	const char *s = json_str(json, NULL);
	return s && s[0] ? g_utf8_make_valid(s, -1) : NULL;
}

/* An address to fetch a picture from: https only */
static char *picture_of(const struct json *json) {
	const char *s = json_str(json, NULL);
	if (s && (g_str_has_prefix(s, "https://") ||
			(sky_allow_http() && g_str_has_prefix(s, "http://")))) {
		return g_strdup(s);
	}
	return NULL;
}

static void set(char **slot, char *value) {
	g_free(*slot);
	*slot = value;
}

static double aspect_of(const struct json *ratio) {
	double w = json_num(json_get(ratio, "width"), 0);
	double h = json_num(json_get(ratio, "height"), 0);
	return w > 0 && h > 0 ? w / h : 0;
}

/* Posts */

static GHashTable *posts; // uri -> struct sky_post, not owned

struct sky_post *sky_post_ref(struct sky_post *p) {
	if (p) {
		p->refs++;
	}
	return p;
}

static void link_free(gpointer data) {
	struct sky_link *l = data;
	g_free(l->label);
	g_free(l->target);
	g_free(l);
}

static void clear_embed(struct sky_post *p) {
	for (int i = 0; i < p->n_images; i++) {
		g_free(p->images[i].thumb);
		g_free(p->images[i].full);
		g_free(p->images[i].alt);
	}
	memset(p->images, 0, sizeof(p->images));
	p->n_images = 0;
	g_clear_pointer(&p->ext_uri, g_free);
	g_clear_pointer(&p->ext_title, g_free);
	g_clear_pointer(&p->ext_text, g_free);
	g_clear_pointer(&p->ext_thumb, g_free);
	g_clear_pointer(&p->video, g_free);
	g_clear_pointer(&p->video_thumb, g_free);
	g_clear_pointer(&p->video_alt, g_free);
	g_clear_pointer(&p->quote_gone, g_free);
	struct sky_post *quote = p->quote;
	p->quote = NULL;
	sky_post_unref(quote);
}

void sky_post_unref(struct sky_post *p) {
	if (p == NULL || --p->refs > 0) {
		return;
	}
	if (posts && g_hash_table_lookup(posts, p->uri) == p) {
		g_hash_table_remove(posts, p->uri);
	}
	clear_embed(p);
	g_free(p->uri);
	g_free(p->cid);
	g_free(p->did);
	g_free(p->handle);
	g_free(p->name);
	g_free(p->avatar);
	g_free(p->text);
	if (p->links) {
		g_ptr_array_unref(p->links);
	}
	g_free(p->like_uri);
	g_free(p->repost_uri);
	g_free(p->root_uri);
	g_free(p->root_cid);
	g_free(p->parent_uri);
	g_free(p->parent_cid);
	g_free(p);
}

struct sky_post *sky_post_find(const char *uri) {
	return posts && uri ? g_hash_table_lookup(posts, uri) : NULL;
}

char *sky_post_web(struct sky_post *p) {
	char *rkey = sky_rkey(p->uri);
	const char *who = p->handle && strcmp(p->handle, "handle.invalid") != 0 ?
		p->handle : p->did;
	char *url = g_strdup_printf("https://bsky.app/profile/%s/post/%s", who,
		rkey);
	g_free(rkey);
	return url;
}

/* The parts of the text the record marks as links, mentions and tags */
static void make_links(struct sky_post *p, const struct json *facets) {
	if (p->links) {
		g_ptr_array_unref(p->links);
	}
	p->links = g_ptr_array_new_with_free_func(link_free);
	size_t len = p->text ? strlen(p->text) : 0;
	for (struct json *f = facets ? facets->child : NULL; f; f = f->next) {
		const struct json *index = json_get(f, "index");
		double s = json_num(json_get(index, "byteStart"), -1);
		double e = json_num(json_get(index, "byteEnd"), -1);
		if (s < 0 || e <= s || e > (double)len) {
			continue;
		}
		const struct json *feature = json_get(f, "features") ?
			json_get(f, "features")->child : NULL;
		const char *type = json_str(json_get(feature, "$type"), "");
		struct sky_link link = { 0 };
		const char *target = NULL;
		if (g_str_has_suffix(type, "#link")) {
			link.kind = SKY_LINK_WEB;
			target = json_str(json_get(feature, "uri"), "");
		} else if (g_str_has_suffix(type, "#mention")) {
			link.kind = SKY_LINK_MENTION;
			target = json_str(json_get(feature, "did"), "");
		} else if (g_str_has_suffix(type, "#tag")) {
			link.kind = SKY_LINK_TAG;
			target = json_str(json_get(feature, "tag"), "");
		}
		if (target == NULL || target[0] == '\0') {
			continue;
		}
		char *label = g_strndup(p->text + (size_t)s, (size_t)(e - s));
		link.label = g_utf8_make_valid(label, -1);
		g_free(label);
		link.target = g_strdup(target);
		g_ptr_array_add(p->links, g_memdup2(&link, sizeof(link)));
	}
}

static void parse_embed(struct sky_post *p, const struct json *embed,
		int depth);

static void parse_quoted(struct sky_post *p, const struct json *record,
		int depth) {
	const char *type = json_str(json_get(record, "$type"), "");
	if (g_str_has_suffix(type, "#viewRecord")) {
		struct sky_post *q = depth < 3 ? sky_post_parse(record) : NULL;
		/* Never a ring */
		for (struct sky_post *c = q; c; c = c->quote) {
			if (c == p) {
				sky_post_unref(q);
				q = NULL;
				break;
			}
		}
		p->quote = q;
	} else if (g_str_has_suffix(type, "#viewNotFound")) {
		p->quote_gone = g_strdup("This post was deleted");
	} else if (g_str_has_suffix(type, "#viewBlocked")) {
		p->quote_gone = g_strdup("A post you can't see: blocked");
	} else if (g_str_has_suffix(type, "#viewDetached")) {
		p->quote_gone = g_strdup("Its author took this post out of the quote");
	} else if (g_str_has_suffix(type, "#generatorView") ||
			g_str_has_suffix(type, "#listView") ||
			g_str_has_suffix(type, "#starterPackViewBasic")) {
		/* A feed or a list: shown as a card that opens it */
		const char *name = json_str(json_get(record, "displayName"),
			json_str(json_get(record, "name"), "Feed"));
		set(&p->ext_title, g_utf8_make_valid(name, -1));
		set(&p->ext_text, text_of(json_get(record, "description")));
		set(&p->ext_uri, g_strdup(json_str(json_get(record, "uri"), "")));
		set(&p->ext_thumb, picture_of(json_get(record, "avatar")));
	}
}

static void parse_embed(struct sky_post *p, const struct json *embed,
		int depth) {
	const char *type = json_str(json_get(embed, "$type"), "");
	if (g_str_has_prefix(type, "app.bsky.embed.images")) {
		for (struct json *i = json_get(embed, "images") ?
				json_get(embed, "images")->child : NULL;
				i && p->n_images < SKY_IMAGES_MAX; i = i->next) {
			struct sky_image *im = &p->images[p->n_images];
			im->thumb = picture_of(json_get(i, "thumb"));
			im->full = picture_of(json_get(i, "fullsize"));
			im->alt = text_of(json_get(i, "alt"));
			im->aspect = aspect_of(json_get(i, "aspectRatio"));
			if (im->thumb) {
				p->n_images++;
			} else {
				g_free(im->full);
				g_free(im->alt);
				memset(im, 0, sizeof(*im));
			}
		}
	} else if (g_str_has_prefix(type, "app.bsky.embed.gallery")) {
		/* As images, its pictures under other names; the first few */
		for (struct json *i = json_get(embed, "items") ?
				json_get(embed, "items")->child : NULL;
				i && p->n_images < SKY_IMAGES_MAX; i = i->next) {
			struct sky_image *im = &p->images[p->n_images];
			im->thumb = picture_of(json_get(i, "thumbnail"));
			if (im->thumb == NULL) {
				continue;
			}
			im->full = picture_of(json_get(i, "fullsize"));
			im->alt = text_of(json_get(i, "alt"));
			im->aspect = aspect_of(json_get(i, "aspectRatio"));
			p->n_images++;
		}
	} else if (g_str_has_prefix(type, "app.bsky.embed.external")) {
		const struct json *ext = json_get(embed, "external");
		const char *uri = json_str(json_get(ext, "uri"), "");
		if (g_str_has_prefix(uri, "https://") ||
				g_str_has_prefix(uri, "http://")) {
			set(&p->ext_uri, g_strdup(uri));
			set(&p->ext_title, text_of(json_get(ext, "title")));
			set(&p->ext_text, text_of(json_get(ext, "description")));
			set(&p->ext_thumb, picture_of(json_get(ext, "thumb")));
		}
	} else if (g_str_has_prefix(type, "app.bsky.embed.video")) {
		set(&p->video, picture_of(json_get(embed, "playlist")));
		set(&p->video_thumb, picture_of(json_get(embed, "thumbnail")));
		set(&p->video_alt, text_of(json_get(embed, "alt")));
		p->video_aspect = aspect_of(json_get(embed, "aspectRatio"));
	} else if (g_str_has_prefix(type, "app.bsky.embed.recordWithMedia")) {
		parse_quoted(p, json_get(json_get(embed, "record"), "record"), depth);
		parse_embed(p, json_get(embed, "media"), depth);
	} else if (g_str_has_prefix(type, "app.bsky.embed.record")) {
		parse_quoted(p, json_get(embed, "record"), depth);
	}
}

static int parse_depth; // posts inside posts being read

struct sky_post *sky_post_parse(const struct json *view) {
	const char *uri = json_str(json_get(view, "uri"), "");
	const struct json *author = json_get(view, "author");
	/* A whole post has its record; one seen inside another, its value */
	const struct json *record = json_get(view, "record");
	bool whole = record != NULL;
	if (!whole) {
		record = json_get(view, "value");
	}
	if (!g_str_has_prefix(uri, "at://") || author == NULL || record == NULL) {
		return NULL;
	}
	if (posts == NULL) {
		posts = g_hash_table_new(g_str_hash, g_str_equal);
	}
	struct sky_post *p = g_hash_table_lookup(posts, uri);
	if (p == NULL) {
		p = g_new0(struct sky_post, 1);
		p->uri = g_strdup(uri);
		p->partial = true;
		g_hash_table_insert(posts, p->uri, p);
	}
	sky_post_ref(p);
	/* A whole one already known isn't made less by a glimpse of it */
	if (!whole && !p->partial) {
		return p;
	}
	p->partial = !whole;
	p->rev++;
	set(&p->cid, g_strdup(json_str(json_get(view, "cid"), "")));
	set(&p->did, g_strdup(json_str(json_get(author, "did"), "")));
	set(&p->handle, g_strdup(json_str(json_get(author, "handle"), "")));
	set(&p->name, text_of(json_get(author, "displayName")));
	if (p->name == NULL) {
		p->name = g_strdup(p->handle);
	}
	char *avatar = picture_of(json_get(author, "avatar"));
	set(&p->avatar, sky_avatar_small(avatar));
	g_free(avatar);
	set(&p->text, text_of(json_get(record, "text")));
	make_links(p, json_get(record, "facets"));
	p->date = sky_parse_time(json_str(json_get(record, "createdAt"), NULL));
	if (p->date == 0) {
		p->date = sky_parse_time(json_str(json_get(view, "indexedAt"), NULL));
	}
	p->replies = (int)json_num(json_get(view, "replyCount"), 0);
	p->reposts = (int)json_num(json_get(view, "repostCount"), 0);
	p->likes = (int)json_num(json_get(view, "likeCount"), 0);
	p->quotes = (int)json_num(json_get(view, "quoteCount"), 0);
	const struct json *viewer = json_get(view, "viewer");
	set(&p->like_uri, g_strdup(json_str(json_get(viewer, "like"), NULL)));
	set(&p->repost_uri, g_strdup(json_str(json_get(viewer, "repost"), NULL)));
	const struct json *reply = json_get(record, "reply");
	const struct json *root = json_get(reply, "root");
	const struct json *parent = json_get(reply, "parent");
	set(&p->root_uri, g_strdup(json_str(json_get(root, "uri"), NULL)));
	set(&p->root_cid, g_strdup(json_str(json_get(root, "cid"), NULL)));
	set(&p->parent_uri, g_strdup(json_str(json_get(parent, "uri"), NULL)));
	set(&p->parent_cid, g_strdup(json_str(json_get(parent, "cid"), NULL)));
	p->sensitive = false;
	for (struct json *l = json_get(view, "labels") ?
			json_get(view, "labels")->child : NULL; l; l = l->next) {
		const char *val = json_str(json_get(l, "val"), "");
		if (strcmp(val, "porn") == 0 || strcmp(val, "sexual") == 0 ||
				strcmp(val, "nudity") == 0 || strcmp(val, "graphic-media") == 0) {
			p->sensitive = true;
		}
	}
	clear_embed(p);
	parse_depth++;
	if (whole) {
		parse_embed(p, json_get(view, "embed"), parse_depth);
	} else {
		const struct json *embeds = json_get(view, "embeds");
		parse_embed(p, embeds ? embeds->child : NULL, parse_depth);
	}
	parse_depth--;
	return p;
}

/* Lists */

void sky_item_free(gpointer data) {
	struct sky_item *it = data;
	sky_post_unref(it->post);
	g_free(it->reason);
	g_free(it->reason_glyph);
	g_free(it->by_did);
	g_free(it->by_name);
	g_free(it->did);
	g_free(it->handle);
	g_free(it->name);
	g_free(it->avatar);
	g_free(it->text);
	g_free(it->follow_uri);
	g_free(it->subject);
	g_free(it);
}

static void item_person(struct sky_item *it, const struct json *who) {
	it->did = g_strdup(json_str(json_get(who, "did"), ""));
	it->handle = g_strdup(json_str(json_get(who, "handle"), ""));
	it->name = text_of(json_get(who, "displayName"));
	if (it->name == NULL) {
		it->name = g_strdup(it->handle);
	}
	char *avatar = picture_of(json_get(who, "avatar"));
	it->avatar = sky_avatar_small(avatar);
	g_free(avatar);
	const struct json *viewer = json_get(who, "viewer");
	it->follow_uri = g_strdup(json_str(json_get(viewer, "following"), NULL));
	it->follows_us = json_get(viewer, "followedBy") != NULL;
}

static char *name_of(const struct json *who) {
	char *name = text_of(json_get(who, "displayName"));
	if (name == NULL) {
		name = g_strdup(json_str(json_get(who, "handle"), "someone"));
	}
	return name;
}

int sky_parse_feed(const struct json *json, GPtrArray *items) {
	int n = 0;
	const struct json *feed = json_get(json, "feed");
	if (feed == NULL) {
		/* A search's posts, or getPosts': bare */
		for (struct json *e = json_get(json, "posts") ?
				json_get(json, "posts")->child : NULL; e; e = e->next) {
			struct sky_post *p = sky_post_parse(e);
			if (p) {
				struct sky_item *it = g_new0(struct sky_item, 1);
				it->post = p;
				g_ptr_array_add(items, it);
				n++;
			}
		}
		return n;
	}
	for (struct json *e = feed->child; e; e = e->next) {
		struct sky_post *p = sky_post_parse(json_get(e, "post"));
		if (p == NULL) {
			continue;
		}
		struct sky_item *it = g_new0(struct sky_item, 1);
		it->post = p;
		const struct json *reason = json_get(e, "reason");
		const char *type = json_str(json_get(reason, "$type"), "");
		const struct json *parent = json_get(json_get(e, "reply"), "parent");
		if (g_str_has_suffix(type, "#reasonRepost")) {
			const struct json *by = json_get(reason, "by");
			it->by_name = name_of(by);
			it->by_did = g_strdup(json_str(json_get(by, "did"), NULL));
			it->reason = g_strdup_printf("Reposted by %s", it->by_name);
			it->reason_glyph = g_strdup("repost");
		} else if (g_str_has_suffix(type, "#reasonPin")) {
			it->reason = g_strdup("Pinned");
			it->reason_glyph = g_strdup("pin");
		} else if (json_get(parent, "author")) {
			const struct json *to = json_get(parent, "author");
			it->by_name = name_of(to);
			it->by_did = g_strdup(json_str(json_get(to, "did"), NULL));
			it->reason = g_strdup_printf("Replying to %s", it->by_name);
			it->reason_glyph = g_strdup("reply");
		} else if (p->parent_uri) {
			it->reason = g_strdup("A reply");
			it->reason_glyph = g_strdup("reply");
		}
		g_ptr_array_add(items, it);
		n++;
	}
	return n;
}

static struct sky_item *gap_item(const char *text, int depth) {
	struct sky_item *it = g_new0(struct sky_item, 1);
	it->kind = SKY_ITEM_GAP;
	it->text = g_strdup(text);
	it->depth = depth;
	return it;
}

static const char *missing(const struct json *node) {
	const char *type = json_str(json_get(node, "$type"), "");
	if (g_str_has_suffix(type, "#blockedPost")) {
		return "A post you can't see: blocked";
	}
	if (g_str_has_suffix(type, "#notFoundPost")) {
		return "This post was deleted";
	}
	return NULL;
}

/* The time a reply was written, for putting them in order */
static int64_t reply_time(const struct json *node) {
	const struct json *post = json_get(node, "post");
	int64_t t = sky_parse_time(json_str(json_get(json_get(post, "record"),
		"createdAt"), NULL));
	return t ? t : sky_parse_time(json_str(json_get(post, "indexedAt"), NULL));
}

static gint by_time(gconstpointer a, gconstpointer b) {
	int64_t ta = reply_time(*(const struct json *const *)a);
	int64_t tb = reply_time(*(const struct json *const *)b);
	return ta < tb ? -1 : ta > tb;
}

/* Depth first, and each post's answers oldest first: the server's order
 * is by its own ranking, which reads as no order at all. GLib's sort is
 * stable, so ties keep the server's. */
static void thread_replies(const struct json *node, GPtrArray *items,
		int depth) {
	GPtrArray *kids = g_ptr_array_new();
	for (struct json *r = json_get(node, "replies") ?
			json_get(node, "replies")->child : NULL; r; r = r->next) {
		g_ptr_array_add(kids, r);
	}
	g_ptr_array_sort(kids, by_time);
	for (guint i = 0; i < kids->len; i++) {
		const struct json *r = kids->pdata[i];
		struct sky_post *p = sky_post_parse(json_get(r, "post"));
		if (p == NULL) {
			const char *why = missing(r);
			if (why) {
				g_ptr_array_add(items, gap_item(why, depth));
			}
			continue;
		}
		struct sky_item *it = g_new0(struct sky_item, 1);
		it->post = p;
		it->depth = depth;
		g_ptr_array_add(items, it);
		if (depth < 8) {
			thread_replies(r, items, depth + 1);
		}
	}
	g_ptr_array_unref(kids);
}

void sky_parse_thread(const struct json *json, GPtrArray *items) {
	const struct json *thread = json_get(json, "thread");
	struct sky_post *p = sky_post_parse(json_get(thread, "post"));
	if (p == NULL) {
		const char *why = missing(thread);
		g_ptr_array_add(items, gap_item(why ? why : "This post can't be shown",
			0));
		return;
	}
	/* What it answers, oldest first */
	guint first = items->len;
	const struct json *up = json_get(thread, "parent");
	for (int i = 0; up && i < 100; i++, up = json_get(up, "parent")) {
		struct sky_post *pp = sky_post_parse(json_get(up, "post"));
		if (pp == NULL) {
			const char *why = missing(up);
			g_ptr_array_insert(items, (int)first, gap_item(why ? why :
				"This post can't be shown", 0));
			break;
		}
		struct sky_item *it = g_new0(struct sky_item, 1);
		it->post = pp;
		g_ptr_array_insert(items, (int)first, it);
	}
	struct sky_item *it = g_new0(struct sky_item, 1);
	it->post = p;
	it->focus = true;
	g_ptr_array_add(items, it);
	/* A line joins each post to the one answering it, down to this one */
	for (guint i = first + 1; i < items->len; i++) {
		struct sky_item *a = items->pdata[i - 1], *b = items->pdata[i];
		if (a->post && b->post) {
			a->chain_down = b->chain_up = true;
		}
	}
	guint answers = items->len;
	thread_replies(thread, items, 0);
	if (items->len > answers) {
		g_ptr_array_insert(items, (int)answers, gap_item(
			"Replies, oldest first", 0));
	}
}

int sky_parse_notices(const struct json *json, GPtrArray *items,
		GPtrArray *need) {
	int n = 0;
	for (struct json *e = json_get(json, "notifications") ?
			json_get(json, "notifications")->child : NULL; e; e = e->next) {
		const char *reason = json_str(json_get(e, "reason"), "");
		const char *says = NULL, *glyph = NULL, *subject = NULL;
		bool whole = false;
		if (strcmp(reason, "like") == 0 ||
				strcmp(reason, "like-via-repost") == 0) {
			says = strcmp(reason, "like") == 0 ? "liked your post" :
				"liked your repost";
			glyph = "like";
			subject = json_str(json_get(e, "reasonSubject"), NULL);
		} else if (strcmp(reason, "repost") == 0 ||
				strcmp(reason, "repost-via-repost") == 0) {
			says = strcmp(reason, "repost") == 0 ? "reposted your post" :
				"reposted your repost";
			glyph = "repost";
			subject = json_str(json_get(e, "reasonSubject"), NULL);
		} else if (strcmp(reason, "follow") == 0) {
			says = "followed you";
			glyph = "follow";
		} else if (strcmp(reason, "reply") == 0) {
			says = "replied to you";
			glyph = "reply";
			whole = true;
		} else if (strcmp(reason, "mention") == 0) {
			says = "mentioned you";
			glyph = "mention";
			whole = true;
		} else if (strcmp(reason, "quote") == 0) {
			says = "quoted you";
			glyph = "quote";
			whole = true;
		} else {
			continue; // kinds this doesn't show
		}
		struct sky_item *it = g_new0(struct sky_item, 1);
		it->kind = SKY_ITEM_NOTICE;
		item_person(it, json_get(e, "author"));
		it->reason = g_strdup(says);
		it->reason_glyph = g_strdup(glyph);
		it->whole = whole;
		it->unread = !json_bool(json_get(e, "isRead"));
		it->date = sky_parse_time(json_str(json_get(e, "indexedAt"), NULL));
		if (whole) {
			subject = json_str(json_get(e, "uri"), NULL);
			/* Until the post comes, its words */
			it->text = text_of(json_get(json_get(e, "record"), "text"));
		}
		if (subject && g_str_has_prefix(subject, "at://")) {
			it->subject = g_strdup(subject);
			struct sky_post *known = sky_post_find(subject);
			if (known && !known->partial) {
				it->post = sky_post_ref(known);
			}
			bool asked = false;
			for (guint i = 0; i < need->len; i++) {
				asked |= strcmp(need->pdata[i], subject) == 0;
			}
			if (!asked) {
				g_ptr_array_add(need, g_strdup(subject));
			}
		}
		g_ptr_array_add(items, it);
		n++;
	}
	return n;
}

void sky_notices_fill(const struct json *json, GPtrArray *items) {
	for (struct json *e = json_get(json, "posts") ?
			json_get(json, "posts")->child : NULL; e; e = e->next) {
		struct sky_post *p = sky_post_parse(e);
		if (p == NULL) {
			continue;
		}
		for (guint i = 0; i < items->len; i++) {
			struct sky_item *it = items->pdata[i];
			if (it->kind == SKY_ITEM_NOTICE && it->subject &&
					strcmp(it->subject, p->uri) == 0 && it->post != p) {
				sky_post_unref(it->post);
				it->post = sky_post_ref(p);
			}
		}
		sky_post_unref(p);
	}
}

int sky_parse_actors(const struct json *array, GPtrArray *items) {
	int n = 0;
	for (struct json *e = array ? array->child : NULL; e; e = e->next) {
		if (json_get(e, "did") == NULL) {
			continue;
		}
		struct sky_item *it = g_new0(struct sky_item, 1);
		it->kind = SKY_ITEM_ACTOR;
		item_person(it, e);
		it->text = text_of(json_get(e, "description"));
		g_ptr_array_add(items, it);
		n++;
	}
	return n;
}

/* People */

struct sky_profile *sky_profile_parse(const struct json *json) {
	if (json_get(json, "did") == NULL) {
		return NULL;
	}
	struct sky_profile *p = g_new0(struct sky_profile, 1);
	p->did = g_strdup(json_str(json_get(json, "did"), ""));
	p->handle = g_strdup(json_str(json_get(json, "handle"), ""));
	p->name = name_of(json);
	p->avatar = picture_of(json_get(json, "avatar"));
	p->banner = picture_of(json_get(json, "banner"));
	p->bio = text_of(json_get(json, "description"));
	p->followers = (int)json_num(json_get(json, "followersCount"), 0);
	p->follows = (int)json_num(json_get(json, "followsCount"), 0);
	p->posts = (int)json_num(json_get(json, "postsCount"), 0);
	const struct json *viewer = json_get(json, "viewer");
	p->follow_uri = g_strdup(json_str(json_get(viewer, "following"), NULL));
	p->block_uri = g_strdup(json_str(json_get(viewer, "blocking"), NULL));
	p->follows_us = json_get(viewer, "followedBy") != NULL;
	p->muted = json_bool(json_get(viewer, "muted"));
	p->blocked_by = json_bool(json_get(viewer, "blockedBy"));
	return p;
}

void sky_profile_free(struct sky_profile *p) {
	if (p == NULL) {
		return;
	}
	g_free(p->did);
	g_free(p->handle);
	g_free(p->name);
	g_free(p->avatar);
	g_free(p->banner);
	g_free(p->bio);
	g_free(p->follow_uri);
	g_free(p->block_uri);
	g_free(p);
}

/* Saved feeds */

void sky_saved_free(gpointer data) {
	struct sky_saved *s = data;
	g_free(s->uri);
	g_free(s->name);
	g_free(s->avatar);
	g_free(s->by);
	g_free(s);
}

GPtrArray *sky_parse_saved(const struct json *prefs) {
	GPtrArray *saved = g_ptr_array_new_with_free_func(sky_saved_free);
	for (struct json *p = json_get(prefs, "preferences") ?
			json_get(prefs, "preferences")->child : NULL; p; p = p->next) {
		const char *type = json_str(json_get(p, "$type"), "");
		if (!g_str_has_suffix(type, "#savedFeedsPrefV2")) {
			continue;
		}
		for (struct json *i = json_get(p, "items") ?
				json_get(p, "items")->child : NULL; i; i = i->next) {
			const char *kind = json_str(json_get(i, "type"), "");
			const char *value = json_str(json_get(i, "value"), "");
			struct sky_saved *s = g_new0(struct sky_saved, 1);
			s->pinned = json_bool(json_get(i, "pinned"));
			if (strcmp(kind, "timeline") == 0) {
				s->uri = g_strdup("following");
				s->name = g_strdup("Following");
			} else if (g_str_has_prefix(value, "at://") &&
					(strcmp(kind, "feed") == 0 || strcmp(kind, "list") == 0)) {
				s->uri = g_strdup(value);
				s->list = strcmp(kind, "list") == 0;
				s->name = g_strdup(s->list ? "List" : "Feed");
			} else {
				sky_saved_free(s);
				continue;
			}
			g_ptr_array_add(saved, s);
		}
	}
	return saved;
}

/* Writing a post */

/* Roughly what a reader sees as one character: marks, joiners and what
 * they join, skin tones and the second half of a flag don't count */
int sky_graphemes(const char *text) {
	int n = 0;
	bool joined = false, flag = false;
	for (const char *p = text; *p; p = g_utf8_next_char(p)) {
		gunichar c = g_utf8_get_char(p);
		if (c == 0x200d) {
			joined = true;
			continue;
		}
		if (g_unichar_ismark(c) || (c >= 0x1f3fb && c <= 0x1f3ff) ||
				(c >= 0xe0020 && c <= 0xe007f)) {
			continue;
		}
		if (joined) {
			joined = false;
			continue;
		}
		if (c >= 0x1f1e6 && c <= 0x1f1ff) {
			flag = !flag;
			if (!flag) {
				continue;
			}
		} else {
			flag = false;
		}
		n++;
	}
	return n;
}

static bool handle_char(char c) {
	return g_ascii_isalnum(c) || c == '.' || c == '-';
}

/* A mention starting at p ("@name.example"): where it ends, NULL if it
 * isn't one */
static const char *mention_end(const char *text, const char *p) {
	if (*p != '@' || (p > text && !g_ascii_isspace(p[-1]) && p[-1] != '(')) {
		return NULL;
	}
	const char *e = p + 1;
	while (handle_char(*e)) {
		e++;
	}
	while (e > p + 1 && (e[-1] == '.' || e[-1] == '-')) {
		e--;
	}
	if (e - p < 4 || memchr(p, '.', (size_t)(e - p)) == NULL) {
		return NULL;
	}
	return e;
}

GPtrArray *sky_mentions_in(const char *text) {
	GPtrArray *found = g_ptr_array_new_with_free_func(g_free);
	for (const char *p = text; *p; p++) {
		const char *e = mention_end(text, p);
		if (e == NULL) {
			continue;
		}
		char *handle = g_ascii_strdown(p + 1, e - p - 1);
		bool have = false;
		for (guint i = 0; i < found->len; i++) {
			have |= strcmp(found->pdata[i], handle) == 0;
		}
		if (have) {
			g_free(handle);
		} else {
			g_ptr_array_add(found, handle);
		}
		p = e - 1;
	}
	return found;
}

static void facet(GString *out, int *count, size_t start, size_t end,
		const char *type, const char *key, const char *value) {
	g_string_append_printf(out, "%s{\"index\":{\"byteStart\":%zu,"
		"\"byteEnd\":%zu},\"features\":[{\"$type\":\"app.bsky.richtext.facet#%s\","
		"\"%s\":", (*count)++ ? "," : "", start, end, type, key);
	sky_json_str(out, value);
	g_string_append(out, "}]}");
}

/* The links, mentions and tags of a text, as the record's facets */
static char *facets_of(const char *text, GHashTable *mentions) {
	GString *out = g_string_new(NULL);
	int count = 0;
	for (const char *p = text; *p; p++) {
		bool start = p == text || g_ascii_isspace(p[-1]) || p[-1] == '(';
		if (!start) {
			continue;
		}
		if (g_str_has_prefix(p, "https://") || g_str_has_prefix(p, "http://")) {
			const char *e = p;
			while (*e && !g_ascii_isspace(*e)) {
				e++;
			}
			/* A full stop after an address is the sentence's */
			while (e > p && strchr(".,;:!?'\"", e[-1])) {
				e--;
			}
			if (e > p && e[-1] == ')' && memchr(p, '(', (size_t)(e - p)) == NULL) {
				e--;
			}
			if (e - p > 10) {
				char *url = g_strndup(p, (size_t)(e - p));
				facet(out, &count, (size_t)(p - text), (size_t)(e - text),
					"link", "uri", url);
				g_free(url);
			}
			p = e > p ? e - 1 : p;
		} else if (*p == '@') {
			const char *e = mention_end(text, p);
			if (e) {
				char *handle = g_ascii_strdown(p + 1, e - p - 1);
				const char *did = mentions ?
					g_hash_table_lookup(mentions, handle) : NULL;
				if (did) {
					facet(out, &count, (size_t)(p - text), (size_t)(e - text),
						"mention", "did", did);
				}
				g_free(handle);
				p = e - 1;
			}
		} else if (*p == '#') {
			const char *e = p + 1;
			bool letters = false;
			while (*e && !g_ascii_isspace(*e)) {
				gunichar c = g_utf8_get_char(e);
				if (g_unichar_ispunct(c) && c != '_') {
					break;
				}
				letters |= !g_unichar_isdigit(c);
				e = g_utf8_next_char(e);
			}
			if (letters && e - p > 1 && e - p <= 65) {
				char *tag = g_strndup(p + 1, (size_t)(e - p - 1));
				facet(out, &count, (size_t)(p - text), (size_t)(e - text),
					"tag", "tag", tag);
				g_free(tag);
			}
			p = e > p + 1 ? e - 1 : p;
		}
	}
	return g_string_free(out, FALSE);
}

static void strong_ref(GString *out, const char *uri, const char *cid) {
	g_string_append(out, "{\"uri\":");
	sky_json_str(out, uri);
	g_string_append(out, ",\"cid\":");
	sky_json_str(out, cid);
	g_string_append_c(out, '}');
}

char *sky_post_record(const char *text, struct sky_post *reply,
		struct sky_post *quote, const char *images, GHashTable *mentions) {
	GString *out = g_string_new("{\"$type\":\"app.bsky.feed.post\",\"text\":");
	sky_json_str(out, text);
	char *now = sky_now_iso();
	g_string_append_printf(out, ",\"createdAt\":\"%s\"", now);
	g_free(now);
	/* The language, from the locale: "en_GB.UTF-8" is en */
	const char *lang = g_get_language_names()[0];
	if (lang && g_ascii_isalpha(lang[0]) && g_ascii_isalpha(lang[1]) &&
			!g_ascii_isalpha(lang[2]) && strcmp(lang, "C") != 0) {
		g_string_append_printf(out, ",\"langs\":[\"%c%c\"]",
			g_ascii_tolower(lang[0]), g_ascii_tolower(lang[1]));
	}
	char *facets = facets_of(text, mentions);
	if (facets[0]) {
		g_string_append_printf(out, ",\"facets\":[%s]", facets);
	}
	g_free(facets);
	if (reply) {
		g_string_append(out, ",\"reply\":{\"root\":");
		if (reply->root_uri && reply->root_cid) {
			strong_ref(out, reply->root_uri, reply->root_cid);
		} else {
			strong_ref(out, reply->uri, reply->cid);
		}
		g_string_append(out, ",\"parent\":");
		strong_ref(out, reply->uri, reply->cid);
		g_string_append_c(out, '}');
	}
	bool pictures = images && images[0];
	if (quote && pictures) {
		g_string_append(out, ",\"embed\":{\"$type\":"
			"\"app.bsky.embed.recordWithMedia\",\"record\":{\"$type\":"
			"\"app.bsky.embed.record\",\"record\":");
		strong_ref(out, quote->uri, quote->cid);
		g_string_append_printf(out, "},\"media\":{\"$type\":"
			"\"app.bsky.embed.images\",\"images\":[%s]}}", images);
	} else if (quote) {
		g_string_append(out, ",\"embed\":{\"$type\":\"app.bsky.embed.record\","
			"\"record\":");
		strong_ref(out, quote->uri, quote->cid);
		g_string_append_c(out, '}');
	} else if (pictures) {
		g_string_append_printf(out, ",\"embed\":{\"$type\":"
			"\"app.bsky.embed.images\",\"images\":[%s]}", images);
	}
	g_string_append_c(out, '}');
	return g_string_free(out, FALSE);
}
