"""Minimal KiCad schematic generator: places symbols, connects pins with stub wires + local labels."""
import copy, os, uuid
from sexp import parse, find, unq, dump, pins as sym_pins

KICAD = r"C:\Program Files\KiCad\10.0\share\kicad"
PROJ_LIBS = {}  # lib nickname -> .kicad_sym path


def U():
    return str(uuid.uuid4())


def q(s):
    return '"' + str(s).replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n') + '"'


_cache = {}


def load_symbol(libid):
    if libid in _cache:
        return _cache[libid]
    lib, name = libid.split(':', 1)
    path = PROJ_LIBS.get(lib) or os.path.join(KICAD, 'symbols', lib + '.kicad_sym')
    tree = parse(open(path, encoding='utf-8').read())
    for c in find(tree, 'symbol'):
        if unq(c[1]) == name:
            assert not find(c, 'extends'), libid + ' uses extends'
            _cache[libid] = c
            return c
    raise KeyError(libid)


def bbox(sym):
    xs, ys = [], []
    def walk(n):
        for c in n:
            if not isinstance(c, list) or not c:
                continue
            if c[0] == 'pin':
                at = find(c, 'at')[0]
                xs.append(float(at[1])); ys.append(float(at[2]))
            elif c[0] == 'rectangle':
                for k in ('start', 'end'):
                    p = find(c, k)[0]; xs.append(float(p[1])); ys.append(float(p[2]))
            elif c[0] == 'polyline':
                for p in find(find(c, 'pts')[0], 'xy'):
                    xs.append(float(p[1])); ys.append(float(p[2]))
            elif c[0] == 'circle':
                ce = find(c, 'center')[0]; r = float(find(c, 'radius')[0][1])
                xs.extend([float(ce[1]) - r, float(ce[1]) + r]); ys.extend([float(ce[2]) - r, float(ce[2]) + r])
            elif c[0] == 'symbol':
                walk(c)
    walk(sym)
    return min(xs), max(xs), min(ys), max(ys)


OUT = {0: (-1, 0), 180: (1, 0), 90: (0, 1), 270: (0, -1)}   # outward direction in schematic coords
LBL = {0: (180, 'right'), 180: (0, 'left'), 90: (270, 'right'), 270: (90, 'left')}


def r2(v):
    return round(v * 100) / 100


class Schematic:
    def __init__(self, project, title, rev, date, company='', paper='B', comments=()):
        self.project, self.title, self.rev, self.date, self.company = project, title, rev, date, company
        self.paper, self.comments = paper, comments
        self.root = U()
        self.items, self.libids, self.intended = [], [], {}
        self.flag_n = 0
        self.points = []  # (x, y, net) of all connection points we create

    def _lib(self, libid):
        if libid not in self.libids:
            self.libids.append(libid)
        return load_symbol(libid)

    def add(self, libid, ref, value, x, y, nets, fp='', dnp=False, props=None, in_bom=True, vpos=None, bom=None):
        sym = self._lib(libid)
        if bom is None:
            bom = in_bom and not ref.startswith(('H', 'JP', 'TP'))
        plist = sym_pins(sym)
        nums = {p[0] for p in plist}
        missing = nums - set(nets)
        extra = set(nets) - nums
        assert not missing and not extra, f'{ref}: missing {missing} extra {extra}'
        lines = [f'(symbol (lib_id {q(libid)}) (at {x} {y} 0) (unit 1) (exclude_from_sim no) (in_bom {"yes" if bom else "no"}) (on_board {"yes" if in_bom else "no"}) (dnp {"yes" if dnp else "no"}) (uuid {q(U())})']
        x0, x1, y0, y1 = bbox(sym)
        two_pin_vert = len(plist) == 2 and all(abs(p[3]) < 0.01 for p in plist)
        hide_val = ref.startswith('#')
        if two_pin_vert:
            rp = (r2(x + 2.54), r2(y - 1.27), 'left'); vp = (r2(x + 2.54), r2(y + 1.27), 'left')
        else:
            rp = (r2(x + x0), r2(y - y1 - 1.27), 'left'); vp = (r2(x + x0), r2(y - y0 + 2.54), 'left')
        if vpos:
            vp = (r2(x + vpos[0]), r2(y + vpos[1]), 'left')
        def prop(k, v, pos, hide=False, just=None):
            j = f' (justify {just})' if just else ''
            h = ' hide' if hide else ''
            return f'(property {q(k)} {q(v)} (at {pos[0]} {pos[1]} 0) (effects (font (size 1.27 1.27)){j}{h}))'
        lines.append(prop('Reference', ref, rp, hide=hide_val, just=rp[2]))
        lines.append(prop('Value', value, vp, hide=hide_val, just=vp[2]))
        lines.append(prop('Footprint', fp, (x, y), hide=True))
        lines.append(prop('Datasheet', (props or {}).pop('Datasheet', ''), (x, y), hide=True))
        lines.append(prop('Description', (props or {}).pop('Description', ''), (x, y), hide=True))
        for k, v in (props or {}).items():
            lines.append(prop(k, v, (x, y), hide=True))
        for p in plist:
            lines.append(f'(pin {q(p[0])} (uuid {q(U())}))')
        lines.append(f'(instances (project {q(self.project)} (path {q("/" + self.root)} (reference {q(ref)}) (unit 1))))')
        lines.append(')')
        self.items.append('\n'.join(lines))
        # connections
        seen = {}
        for num, name, ptype, px, py, ang in plist:
            net = nets[num]
            cx, cy = r2(x + px), r2(y - py)
            if not ref.startswith('#'):
                self.intended[(ref, num)] = net
            key = (cx, cy)
            if key in seen:
                assert seen[key] == net, f'{ref} stacked pins differ'
                continue
            seen[key] = net
            if net is None:
                self.items.append(f'(no_connect (at {cx} {cy}) (uuid {q(U())}))')
                continue
            dx, dy = OUT[ang]
            ex, ey = r2(cx + dx * 2.54), r2(cy + dy * 2.54)
            self.items.append(f'(wire (pts (xy {cx} {cy}) (xy {ex} {ey})) (stroke (width 0) (type default)) (uuid {q(U())}))')
            la, just = LBL[ang]
            self.items.append(f'(label {q(net)} (at {ex} {ey} {la}) (fields_autoplaced yes) (effects (font (size 1.27 1.27)) (justify {just} bottom)) (uuid {q(U())}))')
            self.points.append((cx, cy, net, ref)); self.points.append((ex, ey, net, ref))

    def flag(self, net, x, y):
        self.flag_n += 1
        self.add('power:PWR_FLAG', f'#FLG{self.flag_n:02d}', 'PWR_FLAG', x, y, {'1': net}, in_bom=False)

    # ------------------------------------------------------------------ drawn-wire API
    # place() puts a symbol down without stubs/labels and remembers where each pin ends up, so the
    # caller can draw real wires (wire), power symbols (pwr), labels (label) and no-connects (nc).
    # Junction dots are added automatically in write().

    def _rot(self, px, py, rot):
        """Library pin offset (y up) -> sheet offset (y down) for a symbol rotated by rot (CCW, degrees)."""
        c = {0: (1, 0), 90: (0, 1), 180: (-1, 0), 270: (0, -1)}[rot % 360]
        rx = px * c[0] - py * c[1]
        ry = px * c[1] + py * c[0]
        return rx, -ry

    def place(self, libid, ref, value, x, y, nets, rot=0, fp='', props=None, in_bom=True, ref_at=None, val_at=None,
              hide_value=False, val_just='left'):
        sym = self._lib(libid)
        plist = sym_pins(sym)
        nums = {p[0] for p in plist}
        missing, extra = nums - set(nets), set(nets) - nums
        assert not missing and not extra, f'{ref}: missing {missing} extra {extra}'
        is_pwr = ref.startswith('#')
        bom = in_bom and not is_pwr
        lines = [f'(symbol (lib_id {q(libid)}) (at {x} {y} {rot}) (unit 1) (exclude_from_sim no) (in_bom {"yes" if bom else "no"}) '
                 f'(on_board {"yes" if in_bom and not is_pwr else "no"}) (dnp no) (uuid {q(U())})']
        x0, x1, y0, y1 = bbox(sym)
        # default text positions: to the right of the body (rotation-aware bounding box)
        corners = [self._rot(a, b, rot) for a in (x0, x1) for b in (y0, y1)]
        bx1 = max(c[0] for c in corners); by0 = min(c[1] for c in corners); by1 = max(c[1] for c in corners)
        if ref_at is None:
            ref_at = (r2(x + bx1 + 1.27), r2(y + (by0 + by1) / 2 - 1.27))
        if val_at is None:
            val_at = (r2(x + bx1 + 1.27), r2(y + (by0 + by1) / 2 + 1.27))

        # field angle that keeps text horizontal and left-to-right (checked against KiCad 10 SVG export)
        fang = {0: 0, 90: 270, 180: 0, 270: 90}[rot % 360]

        def prop(k, v, pos, hide=False, just='left'):
            return (f'(property {q(k)} {q(v)} (at {pos[0]} {pos[1]} {fang}) (effects (font (size 1.27 1.27))'
                    f'{" (justify " + just + ")" if just else ""}{" hide" if hide else ""}))')
        lines.append(prop('Reference', ref, ref_at, hide=is_pwr))
        lines.append(prop('Value', value, val_at, hide=hide_value, just=val_just))
        lines.append(prop('Footprint', fp, (x, y), hide=True))
        props = dict(props or {})
        lines.append(prop('Datasheet', props.pop('Datasheet', ''), (x, y), hide=True))
        lines.append(prop('Description', props.pop('Description', ''), (x, y), hide=True))
        for k, v in props.items():
            lines.append(prop(k, v, (x, y), hide=True))
        for p in plist:
            lines.append(f'(pin {q(p[0])} (uuid {q(U())}))')
        lines.append(f'(instances (project {q(self.project)} (path {q("/" + self.root)} (reference {q(ref)}) (unit 1))))')
        lines.append(')')
        self.items.append('\n'.join(lines))
        self.pinpos = getattr(self, 'pinpos', {})
        for num, name, ptype, px, py, ang in plist:
            dx, dy = self._rot(px, py, rot)
            cx, cy = r2(x + dx), r2(y + dy)
            self.pinpos[(ref, num)] = (cx, cy)
            self.points.append((cx, cy, nets[num], ref))
            if not is_pwr:
                self.intended[(ref, num)] = nets[num]
            if nets[num] is None:
                self.items.append(f'(no_connect (at {cx} {cy}) (uuid {q(U())}))')

    def P(self, ref, num):
        return self.pinpos[(ref, str(num))]

    def wire(self, *pts):
        """Orthogonal polyline through the given points (each a pin tuple or (x, y))."""
        pts = [(r2(p[0]), r2(p[1])) for p in pts]
        self.segs = getattr(self, 'segs', [])
        for a, b in zip(pts, pts[1:]):
            if a == b:
                continue
            assert a[0] == b[0] or a[1] == b[1], f'wire not orthogonal: {a} -> {b}'
            self.segs.append((a, b))
            self.items.append(f'(wire (pts (xy {a[0]} {a[1]}) (xy {b[0]} {b[1]})) (stroke (width 0) (type default)) (uuid {q(U())}))')

    def label(self, net, x, y, side='right'):
        """Local net label whose anchor is (x, y); text extends to the given side."""
        ang, just = {'right': (0, 'left'), 'left': (180, 'right'), 'up': (90, 'left'), 'down': (270, 'right')}[side]
        self.items.append(f'(label {q(net)} (at {r2(x)} {r2(y)} {ang}) (fields_autoplaced yes) '
                          f'(effects (font (size 1.27 1.27)) (justify {just} bottom)) (uuid {q(U())}))')

    def pwr(self, net, x, y, toward='up'):
        """Power symbol whose pin is at (x, y). GND draws a ground symbol; anything else a VCC-style bar
        named after the net. toward = direction the symbol body points from (x, y)."""
        self.pwr_n = getattr(self, 'pwr_n', 0) + 1
        ref = f'#PWR{self.pwr_n:03d}'
        if net == 'GND':
            rot = {'down': 0, 'right': 90, 'up': 180, 'left': 270}[toward]
            off = {'down': (0, 5.08), 'right': (3.81, 0), 'up': (0, -5.08), 'left': (-3.81, 0)}[toward]
            self.place('power:GND', ref, 'GND', x, y, {'1': 'GND'}, rot=rot, in_bom=False,
                       ref_at=(x, y + 6.35), val_at=(r2(x + off[0]), r2(y + off[1])), hide_value=True)
        else:
            rot = {'up': 0, 'left': 90, 'down': 180, 'right': 270}[toward]
            off, just = {'up': ((0, -3.81), None), 'left': ((-3.3, 0), 'right'), 'down': ((0, 4.45), None),
                         'right': ((3.3, 0), 'left')}[toward]
            self.place('power:VCC', ref, net, x, y, {'1': net}, rot=rot, in_bom=False,
                       ref_at=(x, y - 6.35), val_at=(r2(x + off[0]), r2(y + off[1])), val_just=just)

    def pflag(self, net, x, y):
        """PWR_FLAG whose pin sits at (x, y) (body above)."""
        self.flag_n += 1
        self.place('power:PWR_FLAG', f'#FLG{self.flag_n:02d}', 'PWR_FLAG', x, y, {'1': net}, in_bom=False,
                   ref_at=(x, y - 5.08), val_at=(r2(x), r2(y - 3.81)), hide_value=True)

    def nc(self, x, y):
        self.items.append(f'(no_connect (at {r2(x)} {r2(y)}) (uuid {q(U())}))')

    def _junctions(self):
        segs = getattr(self, 'segs', [])
        if not segs:
            return
        pins = {}
        for x, y, net, ref in self.points:
            pins[(x, y)] = pins.get((x, y), 0) + 1
        ends = {}
        for a, b in segs:
            for p in (a, b):
                ends[p] = ends.get(p, 0) + 1

        def inside(p, a, b):
            if a[0] == b[0] == p[0]:
                return min(a[1], b[1]) < p[1] < max(a[1], b[1])
            if a[1] == b[1] == p[1]:
                return min(a[0], b[0]) < p[0] < max(a[0], b[0])
            return False
        for p, n in ends.items():
            n += pins.get(p, 0) + 2 * sum(1 for a, b in segs if inside(p, a, b))
            if n >= 3:
                self.items.append(f'(junction (at {p[0]} {p[1]}) (diameter 0) (color 0 0 0 0) (uuid {q(U())}))')
        # a wire end in the middle of another wire must split it for KiCad to connect them; junction above does that

    def text(self, s, x, y, size=1.27, italic=False):
        it = ' italic' if italic else ''
        self.items.append(f'(text {q(s)} (exclude_from_sim no) (at {x} {y} 0) (effects (font (size {size} {size}){it}) (justify left top)) (uuid {q(U())}))')

    def write(self, path):
        self._junctions()
        libs = []
        for libid in self.libids:
            s = copy.deepcopy(load_symbol(libid))
            s[1] = q(libid)
            libs.append(dump(s, 2))
        tb = f'(title_block (title {q(self.title)}) (date {q(self.date)}) (rev {q(self.rev)}) (company {q(self.company)})'
        for i, c in enumerate(self.comments, 1):
            tb += f' (comment {i} {q(c)})'
        tb += ')'
        body = '\n'.join(self.items)
        txt = (f'(kicad_sch (version 20231120) (generator "eeschema") (generator_version "8.0") (uuid {q(self.root)}) (paper {q(self.paper)})\n'
               f'{tb}\n(lib_symbols\n' + '\n'.join(libs) + '\n)\n' + body +
               '\n(sheet_instances (path "/" (page "1")))\n)\n')
        open(path, 'w', encoding='utf-8').write(txt)
