#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "pdfw.h"
#include "render.h"
#include "util.h"

#define MAX_PAGES 500

struct page_size {
	double w, h;
};

static int
fail(char *err, size_t errsz, const char *fmt, const char *arg)
{
	snprintf(err, errsz, fmt, arg);
	return -1;
}

/* --- pdfinfo --------------------------------------------------------------- */

static int
page_sizes(const char *pdf, struct page_size **out)
{
	char small[4096], *big, nbuf[16], *p, *path = (char *)pdf;
	char *argv1[] = { "pdfinfo", path, NULL };
	char *argv2[] = { "pdfinfo", "-f", "1", "-l", nbuf, path, NULL };
	struct page_size *ps;
	int n = 0, pg, rot;
	double w, h;
	size_t bigsz;

	if (run_cmd(argv1, small, sizeof(small)) == -1)
		return -1;
	if ((p = strstr(small, "Pages:")) == NULL ||
	    sscanf(p, "Pages: %d", &n) != 1 || n < 1 || n > MAX_PAGES)
		return -1;
	snprintf(nbuf, sizeof(nbuf), "%d", n);
	bigsz = 4096 + (size_t)n * 512;
	if ((big = malloc(bigsz)) == NULL)
		return -1;
	if ((ps = calloc((size_t)n, sizeof(*ps))) == NULL ||
	    run_cmd(argv2, big, bigsz) == -1) {
		free(big);
		free(ps);
		return -1;
	}
	for (p = big; p != NULL && *p; p = strchr(p, '\n')) {
		if (*p == '\n')
			p++;
		if (sscanf(p, "Page %d size: %lf x %lf pts", &pg, &w, &h) == 3 &&
		    pg >= 1 && pg <= n) {
			ps[pg - 1].w = w;
			ps[pg - 1].h = h;
		} else if (sscanf(p, "Page %d rot: %d", &pg, &rot) == 2 &&
		    pg >= 1 && pg <= n && (rot == 90 || rot == 270)) {
			/* the editor shows the page as displayed, i.e. rotated */
			w = ps[pg - 1].w;
			ps[pg - 1].w = ps[pg - 1].h;
			ps[pg - 1].h = w;
		}
	}
	free(big);
	for (pg = 0; pg < n; pg++)
		if (ps[pg].w <= 0 || ps[pg].h <= 0) {
			free(ps);
			return -1;
		}
	*out = ps;
	return n;
}

int
render_page_size(const char *pdf, int page, double *w, double *h)
{
	struct page_size *ps = NULL;
	int n = page_sizes(pdf, &ps);

	if (n < 1 || page < 1 || page > n) {
		free(ps);
		return -1;
	}
	*w = ps[page - 1].w;
	*h = ps[page - 1].h;
	free(ps);
	return 0;
}

/* --- value resolution ------------------------------------------------------ */

int
series_expand(const char *pat, const char *ymd, int seq, char *out, size_t outsz)
{
	struct tm tm;
	size_t o = 0;
	const char *end;
	char spec[64], piece[128];
	int y, m, d;

	memset(&tm, 0, sizeof(tm));
	if (sscanf(ymd, "%d-%d-%d", &y, &m, &d) != 3)
		return -1;
	tm.tm_year = y - 1900;
	tm.tm_mon = m - 1;
	tm.tm_mday = d;
	tm.tm_isdst = -1;
	mktime(&tm);

	while (*pat) {
		piece[0] = '\0';
		if (*pat == '{' && (end = strchr(pat, '}')) != NULL &&
		    (size_t)(end - pat) < sizeof(spec)) {
			memcpy(spec, pat + 1, (size_t)(end - pat - 1));
			spec[end - pat - 1] = '\0';
			if (strncmp(spec, "date:", 5) == 0) {
				if (strftime(piece, sizeof(piece), spec + 5, &tm) == 0)
					return -1;
			} else if (strcmp(spec, "date") == 0) {
				strftime(piece, sizeof(piece), "%Y%m%d", &tm);
			} else if (strncmp(spec, "seq", 3) == 0) {
				int width = spec[3] == ':' ? atoi(spec + 4) : 1;

				if (width < 1 || width > 12)
					width = 1;
				snprintf(piece, sizeof(piece), "%0*d", width, seq);
			} else
				return -1;
			pat = end + 1;
		} else {
			piece[0] = *pat++;
			piece[1] = '\0';
		}
		if (o + strlen(piece) + 1 > outsz)
			return -1;
		strcpy(out + o, piece);
		o += strlen(piece);
	}
	return 0;
}

/* --- geometry -------------------------------------------------------------- */

static int
bbox(yyjson_val *imp, double b[4])
{
	yyjson_val *coords = yyjson_obj_get(imp, "coords"), *v;
	const char *shape = yyjson_get_str(yyjson_obj_get(imp, "shape"));
	double c[64];
	size_t i, n, max;

	if (!yyjson_is_arr(coords) || (n = yyjson_arr_size(coords)) > 64)
		return -1;
	yyjson_arr_foreach(coords, i, max, v) {
		if (!yyjson_is_num(v))
			return -1;
		c[i] = yyjson_get_num(v);
	}
	if (shape != NULL && strcmp(shape, "circle") == 0) {
		if (n != 3)
			return -1;
		b[0] = c[0] - c[2]; b[1] = c[1] - c[2];
		b[2] = c[0] + c[2]; b[3] = c[1] + c[2];
	} else if (shape != NULL && strcmp(shape, "poly") == 0) {
		if (n < 6 || n % 2)
			return -1;
		b[0] = b[2] = c[0];
		b[1] = b[3] = c[1];
		for (i = 2; i < n; i += 2) {
			if (c[i] < b[0]) b[0] = c[i];
			if (c[i] > b[2]) b[2] = c[i];
			if (c[i + 1] < b[1]) b[1] = c[i + 1];
			if (c[i + 1] > b[3]) b[3] = c[i + 1];
		}
	} else {
		if (n != 4)
			return -1;
		b[0] = c[0] < c[2] ? c[0] : c[2];
		b[1] = c[1] < c[3] ? c[1] : c[3];
		b[2] = c[0] < c[2] ? c[2] : c[0];
		b[3] = c[1] < c[3] ? c[3] : c[1];
	}
	return b[2] - b[0] >= 1 && b[3] - b[1] >= 1 ? 0 : -1;
}

static double
num_or(yyjson_val *obj, const char *key, double def)
{
	yyjson_val *v = yyjson_obj_get(obj, key);

	return yyjson_is_num(v) ? yyjson_get_num(v) : def;
}

/* --- drawing --------------------------------------------------------------- */

static void
draw_text(pdfw *pw, const struct render_ctx *cx, yyjson_val *imp,
    const char *text, double x, double top, double w, double h, double ph)
{
	const char *fref = yyjson_get_str(yyjson_obj_get(imp, "font"));
	const char *align = yyjson_get_str(yyjson_obj_get(imp, "align"));
	char fpath[1024] = "";
	double size, tw, asc, desc, base;
	int font;

	if (fref == NULL || *fref == '\0')
		fref = cx->default_font;
	if (fref != NULL && is_safe_name(fref))
		snprintf(fpath, sizeof(fpath), "%s/%s", cx->asset_dir, fref);
	font = pdfw_font(pw, fpath);

	/* Same fitting rule as www/app.js fitText(): 70% of the box height,
	 * shrunk if needed so the string fits the box width. */
	size = h * 0.7;
	tw = pdfw_text_width(pw, font, text, size);
	if (tw > w && tw > 0) {
		size *= w / tw;
		tw = w;
	}
	pdfw_font_metrics(pw, font, &asc, &desc);
	base = top + (h - (asc - desc) * size) / 2 + asc * size;
	if (align != NULL && strcmp(align, "center") == 0)
		x += (w - tw) / 2;
	else if (align != NULL && strcmp(align, "right") == 0)
		x += w - tw;
	pdfw_text(pw, font, size, x, ph - base, text);
}

static int
draw_image(pdfw *pw, const char *path, double x, double top, double w,
    double h, double ph)
{
	int iw, ih;
	double s, dw, dh;

	if (pdfw_image_size(pw, path, &iw, &ih) == -1)
		return -1;
	/* object-fit: contain, centred */
	s = w / iw < h / ih ? w / iw : h / ih;
	dw = iw * s;
	dh = ih * s;
	return pdfw_image(pw, path, x + (w - dw) / 2,
	    ph - top - h + (h - dh) / 2, dw, dh);
}

static int
draw_imprint(pdfw *pw, const struct render_ctx *cx, yyjson_val *layout,
    yyjson_val *imp, const struct page_size *pg, char *err, size_t errsz)
{
	const char *type = yyjson_get_str(yyjson_obj_get(imp, "type"));
	const char *ref = yyjson_get_str(yyjson_obj_get(imp, "ref"));
	const char *prefix = yyjson_get_str(yyjson_obj_get(imp, "prefix"));
	const char *fmt;
	double b[4], rw, rh, x, top, w, h;
	char text[1024], path[1024];
	const char *val;

	if (type == NULL || bbox(imp, b) == -1)
		return fail(err, errsz, "imprint with bad type or coords%s", "");
	rw = num_or(imp, "ref_w", num_or(layout, "reference_width", 0));
	rh = num_or(imp, "ref_h", num_or(layout, "reference_height", 0));
	if (rw < 1 || rh < 1)
		return fail(err, errsz, "missing reference dimensions%s", "");

	/* HTML pixels -> PostScript points, as ratios of the reference image */
	x = b[0] / rw * pg->w;
	top = b[1] / rh * pg->h;
	w = (b[2] - b[0]) / rw * pg->w;
	h = (b[3] - b[1]) / rh * pg->h;
	if (prefix == NULL)
		prefix = "";

	if (strcmp(type, "resolved_text") == 0) {
		if ((val = yyjson_get_str(yyjson_obj_get(imp, "value"))) == NULL)
			return fail(err, errsz, "missing frozen text%s", "");
		snprintf(text, sizeof(text), "%s%s", prefix, val);
		draw_text(pw, cx, imp, text, x, top, w, h, pg->h);
	} else if (strcmp(type, "serial") == 0) {
		if (cx->serial == NULL)
			return fail(err, errsz, "serial imprint but document has no series%s", "");
		snprintf(text, sizeof(text), "%s%s", prefix, cx->serial);
		draw_text(pw, cx, imp, text, x, top, w, h, pg->h);
	} else if (strcmp(type, "date") == 0) {
		char pat[96], d[128];

		fmt = yyjson_get_str(yyjson_obj_get(imp, "format"));
		if (fmt == NULL || *fmt == '\0' || strlen(fmt) > 64)
			fmt = cx->date_format;
		snprintf(pat, sizeof(pat), "{date:%s}", fmt);
		if (series_expand(pat, cx->doc_date, 0, d, sizeof(d)) == -1)
			return fail(err, errsz, "bad date format: %s", fmt);
		snprintf(text, sizeof(text), "%s%s", prefix, d);
		draw_text(pw, cx, imp, text, x, top, w, h, pg->h);
	} else if (strcmp(type, "frozen_image") == 0) {
		const char *shape = yyjson_get_str(yyjson_obj_get(imp, "shape"));

		if (!is_safe_name(ref))
			return fail(err, errsz, "bad frozen image reference%s", "");
		snprintf(path, sizeof(path), "%s/%s", cx->asset_dir, ref);

		/* Apply circular clipping if shape is "circle" */
		if (shape != NULL && strcmp(shape, "circle") == 0) {
			double cx = x + w / 2;
			double cy = pg->h - top - h / 2;
			double r = (w < h ? w : h) / 2;
			pdfw_clip_circle(pw, cx, cy, r);
		}

		if (draw_image(pw, path, x, top, w, h, pg->h) == -1)
			return fail(err, errsz, "cannot embed image: %s", path);

		/* End clipping if it was applied */
		if (shape != NULL && strcmp(shape, "circle") == 0)
			pdfw_clip_end(pw);
	} else if (strcmp(type, "signature_zone") == 0) {
		/* Signature zones are metadata for the signing flow; skip during rendering */
		return 0;
	} else
		return fail(err, errsz, "unknown imprint type: %s", type);
	return 0;
}

int
render_stamp(const struct render_ctx *cx, yyjson_val *layout, const char *src,
    const char *out, char *err, size_t errsz)
{
	struct page_size *ps = NULL;
	yyjson_val *imps = yyjson_obj_get(layout, "imprints"), *imp;
	char overlay[1024];
	char *argv[] = { "qpdf", "--warning-exit-0", (char *)src, "--overlay",
	    overlay, "--to=1-z", "--from=1-z", "--", (char *)out, NULL };
	size_t i, max;
	pdfw *pw;
	int n, pg, rc = -1;

	if ((n = page_sizes(src, &ps)) == -1)
		return fail(err, errsz, "pdfinfo could not read the source PDF%s", "");
	snprintf(overlay, sizeof(overlay), "%s/overlay-%ld.pdf", cx->tmpdir,
	    (long)getpid());
	if ((pw = pdfw_open(overlay)) == NULL) {
		free(ps);
		return fail(err, errsz, "cannot write %s", overlay);
	}
	for (pg = 1; pg <= n; pg++) {
		pdfw_page(pw, ps[pg - 1].w, ps[pg - 1].h);
		yyjson_arr_foreach(imps, i, max, imp) {
			if ((int)num_or(imp, "page", 1) != pg)
				continue;
			if (draw_imprint(pw, cx, layout, imp, &ps[pg - 1], err,
			    errsz) == -1) {
				pdfw_close(pw);
				goto out;
			}
		}
	}
	if (pdfw_close(pw) == -1) {
		fail(err, errsz, "failed writing overlay%s", "");
		goto out;
	}
	if (run_cmd(argv, NULL, 0) == -1) {
		fail(err, errsz, "qpdf overlay failed%s", "");
		goto out;
	}
	rc = 0;
out:
	unlink(overlay);
	free(ps);
	return rc;
}

static void
audit_line(pdfw *pw, int font, double *y, const char *line)
{
	if (*y < 56) {
		pdfw_page(pw, 595.28, 841.89);
		*y = 841.89 - 72;
	}
	pdfw_text(pw, font, 9.5, 56, *y, line);
	*y -= 15;
}

int
render_release(const struct render_ctx *cx, const char *body, const char *out,
    const char *const *lines, int nlines, char *err, size_t errsz)
{
	const char *fref = cx->default_font;
	char audit[1024], fpath[1024] = "", line[1024];
	char *argv[] = { "qpdf", "--warning-exit-0", "--empty", "--pages",
	    (char *)body, audit, "--", (char *)out, NULL };
	double y = 841.89 - 72;
	pdfw *pw;
	int i, font;

	snprintf(audit, sizeof(audit), "%s/audit-%ld.pdf", cx->tmpdir, (long)getpid());
	if ((pw = pdfw_open(audit)) == NULL)
		return fail(err, errsz, "cannot write %s", audit);
	if (fref != NULL && is_safe_name(fref))
		snprintf(fpath, sizeof(fpath), "%s/%s", cx->asset_dir, fref);
	font = pdfw_font(pw, fpath);
	pdfw_page(pw, 595.28, 841.89);
	pdfw_text(pw, font, 16, 56, y, "Document audit record");
	y -= 30;
	for (i = 0; i < nlines; i++) {
		const char *p = lines[i];
		size_t used = 0;

		/* Wrap complete UTF-8 text instead of dropping comments or event rows. */
		while (*p) {
			const char *next = p;
			size_t bytes;

			utf8_next(&next);
			bytes = (size_t)(next - p);
			if (*p == '\n' || *p == '\r') {
				line[used] = '\0';
				audit_line(pw, font, &y, line);
				used = 0;
				p = next;
				continue;
			}
			if (used + bytes + 1 >= sizeof(line)) {
				line[used] = '\0';
				audit_line(pw, font, &y, line);
				used = 0;
			}
			memcpy(line + used, p, bytes);
			line[used + bytes] = '\0';
			if (used > 0 && pdfw_text_width(pw, font, line, 9.5) > 483) {
				char *space;

				line[used] = '\0';
				space = strrchr(line, ' ');
				if (space != NULL && space != line) {
					size_t rest = used - (size_t)(space - line) - 1;
					*space = '\0';
					audit_line(pw, font, &y, line);
					memmove(line, space + 1, rest);
					used = rest;
				} else {
					audit_line(pw, font, &y, line);
					used = 0;
				}
				continue;
			}
			used += bytes;
			p = next;
		}
		line[used] = '\0';
		audit_line(pw, font, &y, line);
	}
	if (pdfw_close(pw) == -1) {
		unlink(audit);
		return fail(err, errsz, "failed writing audit page%s", "");
	}
	i = run_cmd(argv, NULL, 0);
	unlink(audit);
	if (i == -1)
		return fail(err, errsz, "qpdf merge of audit page failed%s", "");
	return 0;
}

int
render_sign(const struct render_ctx *cx, const char *body, const char *out,
    const char *png, int page, double x, double y, double w, double h,
    double ref_w, double ref_h, char *err, size_t errsz)
{
	struct page_size *ps = NULL;
	char overlay[1024];
	char page_spec[32], from_spec[32];
	char *argv[] = { "qpdf", "--warning-exit-0", (char *)body, "--overlay",
	    overlay, page_spec, from_spec, "--", (char *)out, NULL };
	pdfw *pw;
	int n, iw, ih;
	double fit_w, fit_h;

	if ((n = page_sizes(body, &ps)) == -1)
		return fail(err, errsz, "pdfinfo could not read the body PDF%s", "");
	if (page < 1 || page > n || ref_w <= 0 || ref_h <= 0) {
		free(ps);
		return fail(err, errsz, "invalid signature page or reference size%s", "");
	}
	x = x / ref_w * ps[page - 1].w;
	y = y / ref_h * ps[page - 1].h;
	w = w / ref_w * ps[page - 1].w;
	h = h / ref_h * ps[page - 1].h;

	snprintf(overlay, sizeof(overlay), "%s/sign-%ld.pdf", cx->tmpdir, (long)getpid());
	if ((pw = pdfw_open(overlay)) == NULL) {
		free(ps);
		return fail(err, errsz, "cannot write %s", overlay);
	}
	
	if (pdfw_image_size(pw, png, &iw, &ih) == -1 || iw <= 0 || ih <= 0) {
		pdfw_close(pw);
		free(ps);
		unlink(overlay);
		return fail(err, errsz, "cannot read facsimile %s", png);
	}
	fit_w = w;
	fit_h = w * ih / iw;
	if (fit_h > h) {
		fit_h = h;
		fit_w = h * iw / ih;
	}
	x += (w - fit_w) / 2;
	y += (h - fit_h) / 2;
	w = fit_w;
	h = fit_h;
	pdfw_page(pw, ps[page - 1].w, ps[page - 1].h);
	/* PDF origin is bottom-left; convert placement y from top-left to bottom-left */
	if (pdfw_image(pw, png, x, ps[page - 1].h - y - h, w, h) == -1) {
		pdfw_close(pw);
		free(ps);
		unlink(overlay);
		return fail(err, errsz, "cannot draw image %s", png);
	}
	
	if (pdfw_close(pw) == -1) {
		free(ps);
		unlink(overlay);
		return fail(err, errsz, "failed writing signature overlay%s", "");
	}
	
	snprintf(page_spec, sizeof(page_spec), "--to=%d", page);
	snprintf(from_spec, sizeof(from_spec), "--from=%d", 1);
	
	if (run_cmd(argv, NULL, 0) == -1) {
		free(ps);
		unlink(overlay);
		return fail(err, errsz, "qpdf overlay failed%s", "");
	}
	
	unlink(overlay);
	free(ps);
	return 0;
}
