/*
 *                            COPYRIGHT
 *
 *  sch-rnd - modular/flexible schematics editor - KiCAD netlist export
 *  Copyright (C) 2025 Tibor 'Igor2' Palinkas
 *  Copyright (C) 2025 Aron Barath
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 31 Milk Street, # 960789 Boston, MA 02196 USA.
 *
 *  Contact:
 *    Project page: http://repo.hu/projects/sch-rnd
 *    contact lead developer: http://www.repo.hu/projects/sch-rnd/contact.html
 *    mailing list: http://www.repo.hu/projects/sch-rnd/contact.html
 */


#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <librnd/core/compat_misc.h>
#include <librnd/core/safe_fs.h>
#include <librnd/core/plugins.h>
#include <librnd/core/error.h>
#include <libcschem/config.h>
#include <libcschem/plug_io.h>

#include <plugins/lib_netlist_exp/lib_netlist_exp.h>

static csch_plug_io_t ekicad_net;

static int kicad_export_prio(const char *fn, const char *fmt, csch_plug_io_type_t type)
{
	if (type != CSCH_IOTYP_NETLIST)
		return 0;
	if (rnd_strcasecmp(fmt, "kicad") == 0)
		return 100;
	return 0;
}

static void kicad_print_name(FILE* const f, const char* str)
{
	const char* p;

	p = strchr(str, '\"');

	if(p)
	{
		rnd_message(RND_MSG_WARNING, "kicad: Quotes replaced with underscores: \"%s\"\n", str);

		while(p)
		{
			fwrite(str, p-str, 1, f);

			while((*p)=='\"')
			{
				fputc('_', f);
				++p;
			}

			str = p;

			p = strchr(str, '\"');
		}
	}

	fprintf(f, "%s", str);
}

static void kicad_print_compname(FILE* const f, csch_acomp_t* const comp)
{
	const char* refdes = sch_nle_get_refdes(comp);
	const char* val = sch_nle_get_alt_attr(&comp->hdr.attr, SCH_NLE_ALTATTR_VALUE);
	const char* dev = sch_nle_get_alt_attr(&comp->hdr.attr, SCH_NLE_ALTATTR_DEVICE);

	kicad_print_name(f, refdes);

	if(dev)
	{
		fprintf(f, "___d_");
		kicad_print_name(f, dev);
	}

	if(val)
	{
		fprintf(f, "___v_");
		kicad_print_name(f, val);
	}
}

/* Write a single attribute to f */
static void export_attr(FILE* const f, const char* key, const char* val, const char* indent)
{
	if(key && val)
	{
		fputs(indent, f);
		fputs("(property (name \"", f);
		kicad_print_name(f, key);
		fputs("\") (value \"", f);
		kicad_print_name(f, val);
		fprintf(f, "\"))\n");
	}
}


/* Export comptag and nettag for attributes that have export_name; the user
   wanted these to end up on the netlist as custom tags/attributes/properties */
static void export_custom_attrs(FILE *f, csch_ahdr_t *obj, const char *indent)
{
	htsp_entry_t *e;
	for(e = htsp_first(&obj->attr); e != NULL; e = htsp_next(&obj->attr, e)) {
		csch_attrib_t *a = e->value;
		if ((a->export_name != NULL) && (a->val != NULL)) {
			export_attr(f, a->export_name, a->val, indent);
		}
	}
}

/* Export abstract components into "components" section; exports refdes, */
/* footprint, value, device and all custom attributes */
static void kicad_export_comps(FILE *f, csch_abstract_t *abs)
{
	htsp_entry_t *e;

	fprintf(f, "  (components\n");

	for(e = htsp_first(&abs->comps); e != NULL; e = htsp_next(&abs->comps, e)) {
		csch_acomp_t *comp = e->value;
		const char *refdes = sch_nle_get_refdes(comp);
		const char *fp, *dev, *val;

		if (refdes == NULL)
			continue;

		if (comp->hdr.omit)
			continue;

		/* Get main symbol attributes the safe way, considering alternate names;
		   these should be always exported and are usually hardwiared in the
		   netlist format. */
		fp = sch_nle_get_alt_attr(&comp->hdr.attr, SCH_NLE_ALTATTR_FOOTPRINT);
		val = sch_nle_get_alt_attr(&comp->hdr.attr, SCH_NLE_ALTATTR_VALUE);
		dev = sch_nle_get_alt_attr(&comp->hdr.attr, SCH_NLE_ALTATTR_DEVICE);

		if(!fp) { fp = "~"; }
		if(!dev) { dev = "~"; }

		fprintf(f, "    (comp (ref \"");
		kicad_print_name(f, refdes);
		fprintf(f, "\")\n");

		fprintf(f, "      (value \"");
		kicad_print_name(f, val ? val : dev);
		fprintf(f, "\")\n");

		fprintf(f, "      (footprint \"");
		kicad_print_name(f, fp);
		fprintf(f, "\")\n");

		fprintf(f, "      (description \"");
		kicad_print_name(f, dev);
		fprintf(f, "\")\n");

		fprintf(f, "      (fields\n");
		{
			fprintf(f, "        (field (name \"Footprint\") \"");
			kicad_print_name(f, fp);
			fprintf(f, "\")\n");

			fprintf(f, "        (field (name \"Datasheet\"))\n");

			fprintf(f, "        (field (name \"Description\") \"");
			kicad_print_name(f, dev);
			fprintf(f, "\")\n");
		}
		fprintf(f, "      )\n");

		fprintf(f, "      (libsource (lib \"Device\") (part \"");
		kicad_print_compname(f, comp);
		fprintf(f, "\") (description \"");
		kicad_print_name(f, dev);
		fprintf(f, "\"))\n");

		export_custom_attrs(f, &comp->hdr, "      ");

		fprintf(f, "      (sheetpath (names \"/\") (tstamps \"/\"))\n");
		fprintf(f, "      (tstamps \"/\")\n");
		fprintf(f, "    )\n");
	}

	fprintf(f, "  )\n");
}

struct strlist
{
	struct strlist* next;
	char str[1];
};

static struct strlist* kicad_strlist_find(struct strlist* list, const char* const str)
{
	for(;list;list=list->next)
	{
		if(strcmp(list->str, str)==0)
		{
			return list;
		}
	}

	return NULL;
}

static struct strlist* kicad_strlist_add(struct strlist* list, const char* const str)
{
	struct strlist* n = (struct strlist*)malloc(sizeof(struct strlist)+strlen(str));

	strcpy(n->str, str);
	n->next = list;

	return n;
}

/* Export abstract components into "libparts"; exports crafter component name */
/* value, device and pin names */
static void kicad_export_libparts(FILE *f, csch_abstract_t *abs)
{
	htsp_entry_t *e, *p;
	struct strlist* pinlist;

	fprintf(f, "  (libparts\n");

	for(e = htsp_first(&abs->comps); e != NULL; e = htsp_next(&abs->comps, e)) {
		csch_acomp_t *comp = e->value;
		const char *refdes = sch_nle_get_refdes(comp);
		const char *dev, *val;

		if (refdes == NULL)
			continue;

		if (comp->hdr.omit)
			continue;

		/* Get main symbol attributes the safe way, considering alternate names;
		   these should be always exported and are usually hardwiared in the
		   netlist format. */
		val = sch_nle_get_alt_attr(&comp->hdr.attr, SCH_NLE_ALTATTR_VALUE);
		dev = sch_nle_get_alt_attr(&comp->hdr.attr, SCH_NLE_ALTATTR_DEVICE);

		if(!dev) { dev = "~"; }

		fprintf(f, "    (libpart (lib \"Device\") (part \"");
		kicad_print_compname(f, comp);
		fprintf(f, "\")\n");

		fprintf(f, "      (description \"");
		kicad_print_name(f, dev);
		fprintf(f, "\")\n");

		fprintf(f, "      (docs \"~\")\n");

		fprintf(f, "      (fields\n");
		fprintf(f, "        (field (name \"Reference\") \"~\")\n");
		fprintf(f, "        (field (name \"Value\") \"~\")\n");
		fprintf(f, "        (field (name \"Footprint\"))\n");
		fprintf(f, "        (field (name \"Description\") \"");
		kicad_print_name(f, dev);
		fprintf(f, "\")\n");
		fprintf(f, "      )\n");

		/* this linked list will be used to keep track which pins were */
		/* exported -- typically there is not too much pins, so no worries */
		pinlist = NULL;

		/* Print terminals so that terminal symbolic names can be preserved.
		   (The netlist uses pin number to reference the terminal, symbolic name
		   is just an useful hint) */
		for(p = htsp_first(&comp->ports); p != NULL; p = htsp_next(&comp->ports, p)) {
			const csch_aport_t *port = p->value;
			const char *pinnums = sch_nle_get_pinnum(port);
			const char *pinname = sch_nle_get_alt_attr(&port->hdr.attr, SCH_NLE_ALTATTR_PINNAME);

			if (pinname == NULL)
				continue;

			/* call export_attr on each pin in pinnums (which can be a list of
			   pin numbers) so that each pinnum -> pinname is written */
			SCH_NLE_FOREACH_PINNUM(pinnums, my_num,
				{
					if(!kicad_strlist_find(pinlist, my_num))
					{
						if(!pinlist)
						{
							fprintf(f, "      (pins\n");
						}

						pinlist = kicad_strlist_add(pinlist, my_num);

						fprintf(f, "          (pin (num \"");
						kicad_print_name(f, my_num);
						fprintf(f, "\") (name \"");
						kicad_print_name(f, pinname);
						fprintf(f, "\") (type \"passive\"))\n");
					}
				}
			);
		}

		if(pinlist)
		{
			fprintf(f, "      )\n");
		}

		while(pinlist)
		{
			struct strlist* n = pinlist;
			pinlist = pinlist->next;

			free(n);
		}

		fprintf(f, "    )\n");
	}

	fprintf(f, "  )\n");
}

/* Export abstract nets; export net's name and a list of refdes-pinnum */
/* pairs connected */
static void kicad_export_nets(FILE *f, csch_abstract_t *abs)
{
	htsp_entry_t *e;
	long n;
	long net_code = 1;

	fprintf(f, "  (nets\n");

	for(e = htsp_first(&abs->nets); e != NULL; e = htsp_next(&abs->nets, e)) {
		csch_anet_t *net = e->value;
		const char *netname = sch_nle_get_netname(net);
		int net_exported = 0; /* net had at least one connection so it was written */

		if (net->hdr.omit) continue;

		for(n = 0; n < net->conns.used; n++) {
			csch_aport_t *port = net->conns.array[n];
			const char *refdes = NULL, *pinnums;

			if (port->hdr.type != CSCH_ATYPE_PORT) {
				rnd_message(RND_MSG_ERROR, "kicad: invalid connection (object type)\n");
				continue;
			}

			pinnums = sch_nle_get_pinnum(port);
			if (pinnums == NULL) {
				rnd_message(RND_MSG_ERROR, "kicad: can't determine port's pin number\n");
				continue;
			}

			if (port->parent != NULL) {
				refdes = sch_nle_get_refdes(port->parent);
				if (port->parent->hdr.omit)
					continue; /* omit component */
			}
			if (refdes == NULL) {
				/* This is not an error: no refdes means: do not export (e.g. gnd) */
/*				rnd_message(RND_MSG_ERROR, "kicad: can't determine port's parent component refdes\n");*/
				continue;
			}

			/* split up pinnum at space and create one or more conn lines connecting
			   each pin to the given net */
			SCH_NLE_FOREACH_PINNUM(pinnums, my_num,
				{
					if(!net_exported)
					{
						fprintf(f, "    (net (code \"%li\") (name \"", net_code);
						kicad_print_name(f, netname);
						fprintf(f, "\")\n");

						++net_code;
						net_exported = 1;
					}

					fprintf(f, "      (node (ref \"");
					kicad_print_name(f, refdes);
					fprintf(f, "\") (pin \"");
					kicad_print_name(f, my_num);
					fprintf(f, "\") (pintype \"passive\"))\n");
				}
			);

		}

		/* If the net got exported, then close the block */
		if(net_exported)
		{
			fprintf(f, "    )\n");
		}
	}

	fprintf(f, "  )\n");
}


/* Export netlist from the abstract model */
static int kicad_export_project_abst(const char *fn, const char *fmt, csch_abstract_t *abs, rnd_hid_attr_val_t *options)
{
	TODO("get hidlib as an arg")
	rnd_design_t *hidlib = NULL;
	int i;
	FILE *f = rnd_fopen(hidlib, fn, "w");
	if (f == NULL)
		return -1;

	fprintf(f, "(export (version \"D\")\n");
	fprintf(f, "  (design\n");
	fprintf(f, "    (source \"x\")\n");
	fprintf(f, "    (date \"2025-09-17T15:28:00+0200\")\n");
	fprintf(f, "    (tool \"sch-rnd\")\n");
	fprintf(f, "    (sheet (number \"1\") (name \"/\") (tstamps \"/\")\n");
	fprintf(f, "      (title_block\n");
	fprintf(f, "        (title)\n");
	fprintf(f, "        (company)\n");
	fprintf(f, "        (rev)\n");
	fprintf(f, "        (date)\n");
	fprintf(f, "        (source \"x\")\n");
	for(i=1;i<=9;++i)
		fprintf(f, "        (comment (number \"%i\") (value \"\"))\n", i);
	fprintf(f, "      )\n");
	fprintf(f, "    )\n");
	fprintf(f, "  )\n");

	kicad_export_comps(f, abs);
	kicad_export_libparts(f, abs);

	/* shortcut libraries section, we don't have any */
	fprintf(f, "  (libraries)\n");

	kicad_export_nets(f, abs);

	fprintf(f, ")\n");

	fclose(f);
	return 0;
}

#include "hid_impl.c"

int pplg_check_ver_export_kicad(int ver_needed) { return 0; }

void pplg_uninit_export_kicad(void)
{
	csch_plug_io_unregister(&ekicad_net);
	rnd_export_remove_opts_by_cookie(kicad_cookie);
	rnd_hid_remove_hid(&kicad_hid);
}

int pplg_init_export_kicad(void)
{
	RND_API_CHK_VER;

	ekicad_net.name = "export to KiCAD";
	ekicad_net.export_prio = kicad_export_prio;
	ekicad_net.export_project_abst = kicad_export_project_abst;
	ekicad_net.ext_export_project = ".net";
	csch_plug_io_register(&ekicad_net);


	rnd_hid_nogui_init(&kicad_hid);

	kicad_hid.struct_size = sizeof(rnd_hid_t);
	kicad_hid.name = "kicad";
	kicad_hid.description = "Exports project's KiCAD netlist for pcbnew";
	kicad_hid.exporter = 1;

	kicad_hid.get_export_options = kicad_get_export_options;
	kicad_hid.do_export = kicad_do_export;
	kicad_hid.parse_arguments = kicad_parse_arguments;
	kicad_hid.argument_array = kicad_values;

	kicad_hid.usage = kicad_usage;

	rnd_hid_register_hid(&kicad_hid);
	rnd_hid_load_defaults(&kicad_hid, kicad_options, NUM_OPTIONS);


	return 0;
}

