#include "ignore.h"

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef _WIN32
#include <unistd.h>
#endif

struct ignore_rule {
	char base[IGNORE_PATH_MAX];
	char pattern[1024];
	bool negated;
	bool dir_only;
	bool anchored;
	bool has_slash;
};

static void
path_copy(char *dst, size_t dstsz, const char *src)
{
	snprintf(dst, dstsz, "%s", src ? src : "");
	for (char *p = dst; *p; p++)
		if (*p == '\\')
			*p = '/';
}

static void
trim_trailing_slashes(char *s)
{
	size_t n = strlen(s);
	while (n > 1 && s[n - 1] == '/')
		s[--n] = '\0';
}

void
ignore_init(ignore_context_t *ctx, const char *root)
{
	path_copy(ctx->root, sizeof(ctx->root), root && *root ? root : ".");
	trim_trailing_slashes(ctx->root);
}

bool
ignore_is_ignore_file(const char *path)
{
	char norm[IGNORE_PATH_MAX];
	path_copy(norm, sizeof(norm), path);
	const char *base = strrchr(norm, '/');
	base = base ? base + 1 : norm;
	return strcmp(base, ".gitignore") == 0 || strcmp(base, ".livesideignore") == 0;
}

static bool
is_builtin_ignored(const char *rel)
{
	if (strcmp(rel, ".") == 0 || strcmp(rel, "..") == 0)
		return true;
	const char *p = rel;
	while (*p) {
		const char *slash = strchr(p, '/');
		size_t n = slash ? (size_t)(slash - p) : strlen(p);
		if ((n == 1 && p[0] == '.') || (n == 2 && p[0] == '.' && p[1] == '.') ||
		    (n == 4 && strncmp(p, ".git", 4) == 0))
			return true;
		if (!slash)
			break;
		p = slash + 1;
	}
	return false;
}

static void
relative_to_root(const ignore_context_t *ctx, const char *path,
                 char *rel, size_t relsz)
{
	char norm[IGNORE_PATH_MAX];
	path_copy(norm, sizeof(norm), path);
	trim_trailing_slashes(norm);
	size_t root_len = strlen(ctx->root);
	if (strncmp(norm, ctx->root, root_len) == 0 &&
	    (norm[root_len] == '/' || norm[root_len] == '\0')) {
		const char *r = norm + root_len;
		if (*r == '/')
			r++;
		snprintf(rel, relsz, "%s", *r ? r : ".");
	} else {
		snprintf(rel, relsz, "%s", norm);
	}
}

static bool
unescape_line(char *s)
{
	char *r = s, *w = s;
	while (*r) {
		if (*r == '\\' && r[1])
			r++;
		*w++ = *r++;
	}
	*w = '\0';
	return *s != '\0';
}

static bool
parse_rule(const char *base, char *line, struct ignore_rule *rule)
{
	char *p = line;
	while (*p == ' ' || *p == '\t')
		p++;
	if (*p == '\0')
		return false;
	if (*p == '#' || (*p == '\\' && p[1] == '#')) {
		if (*p == '#')
			return false;
		p++;
	}
	char *end = p + strlen(p);
	while (end > p && (end[-1] == '\n' || end[-1] == '\r'))
		*--end = '\0';
	while (end > p && (end[-1] == ' ' || end[-1] == '\t') &&
	       !(end - 2 >= p && end[-2] == '\\'))
		*--end = '\0';
	if (*p == '\0')
		return false;
	memset(rule, 0, sizeof(*rule));
	snprintf(rule->base, sizeof(rule->base), "%s", base);
	if (*p == '!') {
		rule->negated = true;
		p++;
	}
	if (*p == '/') {
		rule->anchored = true;
		p++;
	}
	size_t len = strlen(p);
	if (len > 0 && p[len - 1] == '/') {
		rule->dir_only = true;
		p[len - 1] = '\0';
	}
	if (!unescape_line(p))
		return false;
	rule->has_slash = strchr(p, '/') != NULL;
	snprintf(rule->pattern, sizeof(rule->pattern), "%s", p);
	return rule->pattern[0] != '\0';
}

static bool
char_match(char pc, char c)
{
	return pc == '?' ? c != '/' && c != '\0' : pc == c;
}

static bool
wildmatch(const char *pat, const char *text)
{
	if (*pat == '\0')
		return *text == '\0';
	if (pat[0] == '*' && pat[1] == '*') {
		pat += 2;
		while (*pat == '*')
			pat++;
		if (*pat == '/') {
			pat++;
			if (wildmatch(pat, text))
				return true;
			for (const char *t = text; *t; t++)
				if (*t == '/' && wildmatch(pat, t + 1))
					return true;
			return false;
		}
		for (const char *t = text;; t++) {
			if (wildmatch(pat, t))
				return true;
			if (*t == '\0')
				return false;
		}
	}
	if (*pat == '*') {
		pat++;
		for (const char *t = text;; t++) {
			if (wildmatch(pat, t))
				return true;
			if (*t == '\0' || *t == '/')
				return false;
		}
	}
	return char_match(*pat, *text) && wildmatch(pat + 1, text + 1);
}

static bool
match_basename(const char *pattern, const char *rel)
{
	const char *p = rel;
	while (*p) {
		const char *slash = strchr(p, '/');
		size_t n = slash ? (size_t)(slash - p) : strlen(p);
		char comp[1024];
		if (n >= sizeof(comp))
			n = sizeof(comp) - 1;
		memcpy(comp, p, n);
		comp[n] = '\0';
		if (wildmatch(pattern, comp))
			return true;
		if (!slash)
			break;
		p = slash + 1;
	}
	return false;
}

static bool
rule_matches(const struct ignore_rule *rule, const char *rel, bool is_dir)
{
	char scoped[IGNORE_PATH_MAX];
	if (rule->base[0]) {
		size_t n = strlen(rule->base);
		if (strncmp(rel, rule->base, n) != 0 || (rel[n] != '/' && rel[n] != '\0'))
			return false;
		const char *r = rel + n;
		if (*r == '/')
			r++;
		snprintf(scoped, sizeof(scoped), "%s", *r ? r : ".");
	} else {
		snprintf(scoped, sizeof(scoped), "%s", rel);
	}
	if (rule->dir_only) {
		if (is_dir && (wildmatch(rule->pattern, scoped) || match_basename(rule->pattern, scoped)))
			return true;
		char prefix[1024];
		snprintf(prefix, sizeof(prefix), "%s/", rule->pattern);
		return strncmp(scoped, prefix, strlen(prefix)) == 0 ||
		       (!rule->anchored && strstr(scoped, prefix) != NULL);
	}
	if (rule->anchored || rule->has_slash)
		return wildmatch(rule->pattern, scoped);
	return match_basename(rule->pattern, scoped);
}

static void
load_file_rules(const char *root, const char *base, const char *name,
                const char *rel, bool is_dir, bool *ignored)
{
	char file[IGNORE_PATH_MAX];
	if (base[0])
		snprintf(file, sizeof(file), "%s/%s/%s", root, base, name);
	else
		snprintf(file, sizeof(file), "%s/%s", root, name);
	FILE *fp = fopen(file, "r");
	if (!fp)
		return;
	char line[2048];
	while (fgets(line, sizeof(line), fp)) {
		struct ignore_rule rule;
		if (parse_rule(base, line, &rule) && rule_matches(&rule, rel, is_dir))
			*ignored = !rule.negated;
	}
	fclose(fp);
}

bool
ignore_path_ignored(const ignore_context_t *ctx, const char *path, bool is_dir)
{
	char rel[IGNORE_PATH_MAX];
	relative_to_root(ctx, path, rel, sizeof(rel));
	if (is_builtin_ignored(rel))
		return true;
	bool ignored = false;
	char base[IGNORE_PATH_MAX] = "";
	load_file_rules(ctx->root, base, ".gitignore", rel, is_dir, &ignored);
	load_file_rules(ctx->root, base, ".livesideignore", rel, is_dir, &ignored);
	char walk[IGNORE_PATH_MAX];
	snprintf(walk, sizeof(walk), "%s", rel);
	char *slash = walk;
	while ((slash = strchr(slash, '/')) != NULL) {
		*slash = '\0';
		snprintf(base, sizeof(base), "%s", walk);
		load_file_rules(ctx->root, base, ".gitignore", rel, is_dir, &ignored);
		load_file_rules(ctx->root, base, ".livesideignore", rel, is_dir, &ignored);
		*slash++ = '/';
	}
	return ignored;
}
