#ifndef SKY_H
#define SKY_H

#include <cairo.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <stdbool.h>
#include <stdint.h>
#include "json.h"

#define APP_ID "org.cont8nuum.Cirrus"
#define TILE_WIDGET_ID "c8-cirrus" /* the tile made from c8-cirrus.widget */
#define SKY_AGENT "c8-cirrus/0.1 (cont8nuum)"
#define SKY_TEXT_MAX 300 /* graphemes in a post */
#define SKY_IMAGES_MAX 4

/* An account signed in to: who, and the server (PDS) that holds it. The
 * session's two tokens are in the wallet, never in a file. */
struct sky_account {
	char *did, *handle, *pds;
	char *name, *avatar; // as last seen, for the accounts page
	char *access, *refresh; // NULL until read from the wallet
	bool loaded; // the wallet was asked
	bool expired; // the server won't renew the session: sign in again
};

struct sky_settings {
	bool images; // pictures in posts
	bool sensitive; // show pictures labelled as adult or graphic
	bool toasts; // notifications from the tile provider
	int text_size; // 0 small, 1 medium, 2 large
};

extern struct sky_settings sky_settings;
extern GPtrArray *sky_accounts; // struct sky_account
extern struct sky_account *sky_me; // the one in use, NULL: signed out

/* store.c: cirrus.ini and where the cache is */
void sky_load(void);
void sky_save(void);
char *sky_cache_path(const char *name); // under ~/.cache/cont8nuum/cirrus
char *sky_state_path(const char *name); // under ~/.local/state/cont8nuum/cirrus
struct sky_account *sky_account_find(const char *did);
struct sky_account *sky_account_add(const char *did, const char *handle,
	const char *pds);
void sky_account_remove(struct sky_account *a); // frees it
bool sky_allow_http(void); // tests against a local mock

/* session.c: signing in, the tokens, and every call to the server */

/* error NULL: it worked */
typedef void (*sky_done_fn)(const char *error, void *data);
/* identifier: a handle, a DID or the account's email; server: where the
 * account is, or NULL or "" to find it from the handle. The account
 * becomes sky_me. */
void sky_sign_in(const char *identifier, const char *password,
	const char *server, sky_done_fn fn, void *data);
/* Ends the session on the server, forgets its tokens and the account */
void sky_sign_out(struct sky_account *a);
/* Another account from now on: calls still out for the old one answer
 * with status 0 and no error */
void sky_use(struct sky_account *a);
/* Changes with every sky_use and sign in or out: what a late answer
 * compares to know it is about the account still in use */
extern unsigned sky_generation;
/* Runs when the account in use can't go on (its session ended) */
void sky_on_expired(void (*fn)(void *data), void *data);

/* status: the HTTP one, 0 if the server wasn't reached. error: words to
 * show for anything but a 200 (NULL when quietly dropped: the account
 * changed meanwhile). json is freed after fn returns. */
typedef void (*sky_fn)(int status, struct json *json, const char *error,
	void *data);
/* call is the method with its query: "app.bsky.feed.getTimeline?limit=30" */
void sky_get(const char *call, sky_fn fn, void *data);
void sky_post(const char *method, const char *body, sky_fn fn, void *data);
/* A file's bytes as a blob: the answer has "blob" to put in a record */
void sky_upload(const char *path, const char *mime, sky_fn fn, void *data);
/* Without an account, from the public server (signing in, a handle) */
void sky_get_public(const char *url, sky_fn fn, void *data);

/* Building calls and JSON */
void sky_query(GString *call, const char *key, const char *value); // &key=value, escaped
void sky_json_str(GString *out, const char *text); // "text", escaped
char *sky_now_iso(void); // 2026-01-02T03:04:05.000Z
int64_t sky_parse_time(const char *iso); // unix seconds, 0 if it isn't one
char *sky_age(int64_t date); // "3m", "2h", "5d", then the date
char *sky_rkey(const char *uri); // the last part of an at:// address

/* model.c: what the server says, as structs */

struct sky_image {
	char *thumb, *full, *alt;
	double aspect; // width / height, 0: not said
};

enum sky_link_kind { SKY_LINK_WEB, SKY_LINK_MENTION, SKY_LINK_TAG };

struct sky_link {
	enum sky_link_kind kind;
	char *label; // the words in the post
	char *target; // an address, a DID, a tag
};

/* A post as shown. One struct per post however many lists it is in (they
 * are looked up by address), so a like shows everywhere. */
struct sky_post {
	int refs;
	char *uri, *cid;
	char *did, *handle, *name, *avatar; // who wrote it
	char *text;
	GPtrArray *links; // struct sky_link
	int64_t date;
	int replies, reposts, likes, quotes;
	char *like_uri, *repost_uri; // ours, if we did
	struct sky_image images[SKY_IMAGES_MAX];
	int n_images;
	char *ext_uri, *ext_title, *ext_text, *ext_thumb; // a link card
	char *video, *video_thumb, *video_alt; // the playlist's address
	double video_aspect;
	struct sky_post *quote; // the post it quotes
	char *quote_gone; // or why that can't be shown
	bool sensitive; // labelled adult or graphic
	/* What it answers, for a reply to it to carry on */
	char *root_uri, *root_cid, *parent_uri, *parent_cid;
	bool partial; // seen only inside another post: no counts
	uint32_t rev; // goes up when anything shown changes
};

struct sky_post *sky_post_ref(struct sky_post *p);
void sky_post_unref(struct sky_post *p);
/* From a postView or an embedded record view; NULL if it is neither */
struct sky_post *sky_post_parse(const struct json *view);
struct sky_post *sky_post_find(const char *uri); // not a new reference
char *sky_post_web(struct sky_post *p); // its page on bsky.app

enum sky_item_kind {
	SKY_ITEM_POST,
	SKY_ITEM_NOTICE, // a like, a repost, a follow: a line and its subject
	SKY_ITEM_ACTOR, // a person: search results, followers
	SKY_ITEM_MORE, // the end of what is loaded: asking for it loads more
	SKY_ITEM_GAP, // replies left out of a thread
};

/* An entry of a list: a post and why it is there */
struct sky_item {
	enum sky_item_kind kind;
	struct sky_post *post; // may be NULL (a notice of a follow)
	char *reason; // "Reposted by …", "Replied to you"
	char *by_did, *by_name; // who the reason ends with, if anyone
	char *reason_glyph; // repost, reply, like, follow, quote, mention, pin
	int depth; // a thread's replies: how far in
	bool focus; // the post a thread page is about
	bool chain_up, chain_down; // a thread's line to the post above, below
	bool unread;
	/* Notices and people */
	char *did, *handle, *name, *avatar, *text;
	char *follow_uri; // people: our follow of them
	char *subject; // notices: the address of the post it is about
	bool whole; // notices: the post is the news itself (a reply to us)
	bool follows_us;
	int64_t date;
};

void sky_item_free(gpointer item);
/* A feed's answer (getTimeline, getFeed, getAuthorFeed, searchPosts…)
 * added to items; returns how many */
int sky_parse_feed(const struct json *json, GPtrArray *items);
/* getPostThread's answer flattened: parents, the post (focus), replies */
void sky_parse_thread(const struct json *json, GPtrArray *items);
/* listNotifications: items whose posts are to come. need gets the
 * addresses to ask getPosts for; sky_notices_fill puts the answer in */
int sky_parse_notices(const struct json *json, GPtrArray *items,
	GPtrArray *need);
void sky_notices_fill(const struct json *posts, GPtrArray *items);
int sky_parse_actors(const struct json *array, GPtrArray *items);

struct sky_profile {
	char *did, *handle, *name, *avatar, *banner, *bio;
	int followers, follows, posts;
	char *follow_uri, *block_uri; // ours
	bool follows_us, muted, blocked_by;
};

struct sky_profile *sky_profile_parse(const struct json *json);
void sky_profile_free(struct sky_profile *p);

/* A feed or a list saved in the account's preferences */
struct sky_saved {
	char *uri; // at://… ; "following" for the timeline
	char *name, *avatar, *by;
	bool list, pinned;
};

void sky_saved_free(gpointer saved);
/* getPreferences' answer: the saved feeds in their order, names to come */
GPtrArray *sky_parse_saved(const struct json *prefs);

/* A new post's JSON record. reply and quote may be NULL; blobs is the
 * JSON of each uploaded picture ("image", "alt", "aspectRatio" members),
 * joined by commas, or NULL. mentions: handle -> DID for those found. */
char *sky_post_record(const char *text, struct sky_post *reply,
	struct sky_post *quote, const char *images, GHashTable *mentions);
/* The @handles in a text, to look up before sky_post_record */
GPtrArray *sky_mentions_in(const char *text);
int sky_graphemes(const char *text);

/* image.c: pictures, fetched into the cache and decoded on demand */
typedef void (*sky_image_fn)(const char *url, void *data);
void sky_image_on_ready(sky_image_fn fn, void *data);
/* The picture no bigger than 640 px, or NULL while it comes or if it
 * can't; asking starts the download. Not the caller's to destroy. */
cairo_surface_t *sky_image(const char *url);
/* Set when sky_image said NULL for one on its way: what was drawn then
 * is not how it will look */
extern bool sky_image_missed;
/* Up to 2560 px, for a picture across the window; two are kept */
cairo_surface_t *sky_image_large(const char *url);
const char *sky_image_path(const char *url); // the file once downloaded
void sky_image_fetch(const char *url); // download it, decode nothing
/* An avatar's address at the small size the CDN has */
char *sky_avatar_small(const char *url);

/* shown.c: stealth mode. What is drawn of the accounts signed in here
 * goes through these: while it's on, the persona's name and handle and
 * no picture instead. The structs keep the real ones for the calls. */
bool sky_mine(const char *did); // one of ours, and stealth is on
const char *sky_shown_name(const char *did, const char *name);
const char *sky_shown_handle(const char *did, const char *handle);
const char *sky_shown_avatar(const char *did, const char *url); // NULL: ours
/* @handles of ours in a post's words made the persona's; kept strings */
const char *sky_shown_text(const char *text);
char *sky_shown_reason(const struct sky_item *it); // newly allocated

/* tile.c: the live tile over org.cont8nuum.Tiles1 */
void sky_tile_update(const char *tile_id, GPtrArray *items, int unread);
void sky_tile_clear(const char *tile_id);

#endif
