"""Build the shared project library (symbols + footprints) for the XFM5050UV designs."""
import copy, os, sys
sys.path.insert(0, os.path.dirname(__file__))
from sexp import parse, find, unq, dump

ORIG, DEST = sys.argv[1], sys.argv[2]
LIB = os.path.join(DEST, 'lib')
os.makedirs(os.path.join(LIB, 'XFM5050UV.pretty'), exist_ok=True)


def embedded(fname, libid):
    tree = parse(open(os.path.join(ORIG, fname), encoding='utf-8').read())
    for c in find(find(tree, 'lib_symbols')[0], 'symbol'):
        if unq(c[1]) == libid:
            return copy.deepcopy(c)
    raise KeyError(libid)


def set_prop(sym, key, val):
    for p in find(sym, 'property'):
        if unq(p[1]) == key:
            p[2] = '"' + val + '"'
            return
    raise KeyError(key)


syms = []
for fname, libid, fp, ds in [
        ('LEDDrivers.kicad_sch', 'ProjectDevices:iC-HG30', 'Package_DFN_QFN:QFN-28-1EP_5x5mm_P0.5mm_EP3.75x3.75mm_ThermalVias', 'https://www.ichaus.de/product/ic-hg30/'),
        ('LEDDrivers.kicad_sch', 'ProjectDevices:AD5669R', 'Package_SO:TSSOP-16_4.4x5mm_P0.65mm', 'https://www.analog.com/en/products/ad5669r.html'),
        ('INA209.kicad_sch', 'ProjectDevices:INA209', 'Package_SO:TSSOP-16_4.4x5mm_P0.65mm', 'https://www.ti.com/lit/ds/symlink/ina209.pdf')]:
    s = embedded(fname, libid)
    s[1] = '"' + libid.split(':')[1] + '"'
    set_prop(s, 'Footprint', fp)
    set_prop(s, 'Datasheet', ds)
    syms.append(dump(s, 1))

# Luminus XFM-5050-UV: pin 1 anode, 2 cathode, 3 thermal pad
syms.append('''(symbol "XFM-5050-UV" (pin_names (offset 0.762)) (exclude_from_sim no) (in_bom yes) (on_board yes)
	(property "Reference" "D" (at -5.08 6.35 0) (effects (font (size 1.27 1.27)) (justify left)))
	(property "Value" "XFM-5050-UV" (at -5.08 -8.89 0) (effects (font (size 1.27 1.27)) (justify left)))
	(property "Footprint" "XFM5050UV:XFM-5050-UV" (at 0 0 0) (effects (font (size 1.27 1.27)) hide))
	(property "Datasheet" "https://download.luminus.com/datasheets/Luminus_XFM-5050-UV_Datasheet.pdf" (at 0 0 0) (effects (font (size 1.27 1.27)) hide))
	(property "Description" "Luminus XFM-5050-UV 4-chip UVC LED, 275 nm, 5.0x5.0 mm, If 2 A typ / 3.2 A max" (at 0 0 0) (effects (font (size 1.27 1.27)) hide))
	(property "ki_keywords" "LED UVC UV-C 275nm Luminus" (at 0 0 0) (effects (font (size 1.27 1.27)) hide))
	(symbol "XFM-5050-UV_0_1"
		(rectangle (start -5.08 3.81) (end 5.08 -5.08) (stroke (width 0.254) (type default)) (fill (type background)))
		(polyline (pts (xy -1.27 1.27) (xy 1.27 0) (xy -1.27 -1.27) (xy -1.27 1.27)) (stroke (width 0.254) (type default)) (fill (type outline)))
		(polyline (pts (xy 1.27 1.27) (xy 1.27 -1.27)) (stroke (width 0.254) (type default)) (fill (type none)))
		(polyline (pts (xy -5.08 0) (xy -1.27 0)) (stroke (width 0) (type default)) (fill (type none)))
		(polyline (pts (xy 1.27 0) (xy 5.08 0)) (stroke (width 0) (type default)) (fill (type none)))
		(polyline (pts (xy 0 1.524) (xy 1.016 2.54) (xy 0.508 2.54) (xy 1.016 2.54) (xy 1.016 2.032)) (stroke (width 0) (type default)) (fill (type none)))
		(polyline (pts (xy 1.016 1.524) (xy 2.032 2.54) (xy 1.524 2.54) (xy 2.032 2.54) (xy 2.032 2.032)) (stroke (width 0) (type default)) (fill (type none)))
	)
	(symbol "XFM-5050-UV_1_1"
		(pin passive line (at -7.62 0 0) (length 2.54) (name "A" (effects (font (size 1.27 1.27)))) (number "1" (effects (font (size 1.27 1.27)))))
		(pin passive line (at 7.62 0 180) (length 2.54) (name "K" (effects (font (size 1.27 1.27)))) (number "2" (effects (font (size 1.27 1.27)))))
		(pin passive line (at 0 -7.62 90) (length 2.54) (name "TH" (effects (font (size 1.27 1.27)))) (number "3" (effects (font (size 1.27 1.27)))))
	)
)''')



def ic(name, value, fp, ds, desc, pins, w=7.62, h=7.62):
    """Simple box symbol. pins: (number, name, type, x, y, angle) with the pin's connection point at (x, y)."""
    body = ''.join(
        f'\n\t\t\t(pin {t} line (at {x} {y} {a}) (length 2.54) (name "{n}" (effects (font (size 1.27 1.27)))) '
        f'(number "{num}" (effects (font (size 1.27 1.27)))))' for num, n, t, x, y, a in pins)
    return f'''(symbol "{name}" (pin_names (offset 0.762)) (exclude_from_sim no) (in_bom yes) (on_board yes)
	(property "Reference" "U" (at {-w} {h + 1.27} 0) (effects (font (size 1.27 1.27)) (justify left)))
	(property "Value" "{value}" (at {-w} {-h - 1.27} 0) (effects (font (size 1.27 1.27)) (justify left)))
	(property "Footprint" "{fp}" (at 0 0 0) (effects (font (size 1.27 1.27)) hide))
	(property "Datasheet" "{ds}" (at 0 0 0) (effects (font (size 1.27 1.27)) hide))
	(property "Description" "{desc}" (at 0 0 0) (effects (font (size 1.27 1.27)) hide))
	(symbol "{name}_0_1"
		(rectangle (start {-w} {h}) (end {w} {-h}) (stroke (width 0.254) (type default)) (fill (type background)))
	)
	(symbol "{name}_1_1"{body}
	)
)'''


# TI INA236, SOT-23-8 (DDF): 1 IN+, 2 IN-, 3 GND, 4 VS, 5 SCL, 6 SDA, 7 A0, 8 ALERT (datasheet SBOSA81 pin diagram)
syms.append(ic('INA236', 'INA236', 'Package_TO_SOT_SMD:SOT-23-8', 'https://www.ti.com/lit/ds/symlink/ina236.pdf',
               '48 V 16-bit I2C current/voltage/power monitor, external shunt, SOT-23-8',
               [('1', 'IN+', 'passive', -10.16, 2.54, 0), ('2', 'IN-', 'passive', -10.16, -2.54, 0),
                ('4', 'VS', 'power_in', 0, 10.16, 270), ('3', 'GND', 'power_in', 0, -10.16, 90),
                ('5', 'SCL', 'input', 10.16, 5.08, 180), ('6', 'SDA', 'bidirectional', 10.16, 2.54, 180),
                ('7', 'A0', 'input', 10.16, -2.54, 180), ('8', 'ALERT', 'open_collector', 10.16, -5.08, 180)]))
# ADI AD5693R, 8-lead LFCSP (CP-8-10), LDAC option (AD5693RACPZ): 1 VDD, 2 LDAC, 3 GND, 4 A0, 5 SCL, 6 SDA,
# 7 VREF, 8 VOUT, EPAD to GND (datasheet Rev. D, Table 8)
syms.append(ic('AD5693R_LFCSP', 'AD5693RACPZ', 'Package_DFN_QFN:DFN-8-1EP_2x2mm_P0.5mm_EP0.6x1.2mm',
               'https://www.analog.com/en/products/ad5693r.html',
               '16-bit I2C DAC, 2.5 V internal reference (on by default), gain 1/2 by control register, LFCSP-8 2x2 mm',
               [('1', 'VDD', 'power_in', 0, 12.7, 270), ('3', 'GND', 'power_in', -2.54, -12.7, 90),
                ('9', 'EP', 'passive', 2.54, -12.7, 90),
                ('5', 'SCL', 'input', -10.16, 5.08, 0), ('6', 'SDA', 'bidirectional', -10.16, 2.54, 0),
                ('4', 'A0', 'input', -10.16, -2.54, 0), ('2', '~{LDAC}', 'input', -10.16, -5.08, 0),
                ('8', 'VOUT', 'output', 10.16, 2.54, 180), ('7', 'VREF', 'passive', 10.16, -2.54, 180)], h=10.16))

open(os.path.join(LIB, 'XFM5050UV.kicad_sym'), 'w', encoding='utf-8').write(
    '(kicad_symbol_lib (version 20231120) (generator "kicad_symbol_editor") (generator_version "8.0")\n' + '\n'.join(syms) + '\n)\n')

# Footprint from Luminus PDS-003131 Rev01 p.7 (top view: cathode left, anode right).
# Copper = device metallization; paste = recommended stencil apertures (0.64x4.04, 1.76x4.04).
vias = ''.join(f'\n\t(pad "3" thru_hole circle (at {x} {y}) (size 0.5 0.5) (drill 0.25) (layers "*.Cu") (zone_connect 2))'
               for x in (-0.55, 0.55) for y in (-1.8, -0.9, 0, 0.9, 1.8))
fp = f'''(footprint "XFM-5050-UV" (version 20240108) (generator "pcbnew") (generator_version "8.0") (layer "F.Cu")
	(descr "Luminus XFM-5050-UV 4-chip UVC LED, 5.2x5.2 mm body; pads per PDS-003131 Rev 01 page 7; 10 thermal vias in centre pad (fill/cap or tent for reflow)")
	(tags "LED UVC Luminus XFM 5050")
	(property "Reference" "REF**" (at 0 -4.1 0) (layer "F.SilkS") (effects (font (size 1 1) (thickness 0.15))))
	(property "Value" "XFM-5050-UV" (at 0 4.1 0) (layer "F.Fab") (effects (font (size 1 1) (thickness 0.15))))
	(property "Footprint" "" (at 0 0 0) (layer "F.Fab") hide (effects (font (size 1.27 1.27))))
	(property "Datasheet" "https://download.luminus.com/datasheets/Luminus_XFM-5050-UV_Datasheet.pdf" (at 0 0 0) (layer "F.Fab") hide (effects (font (size 1.27 1.27))))
	(property "Description" "" (at 0 0 0) (layer "F.Fab") hide (effects (font (size 1.27 1.27))))
	(attr smd)
	(fp_line (start -2.6 -2.6) (end 2.6 -2.6) (stroke (width 0.1) (type solid)) (layer "F.Fab"))
	(fp_line (start 2.6 -2.6) (end 2.6 2.6) (stroke (width 0.1) (type solid)) (layer "F.Fab"))
	(fp_line (start 2.6 2.6) (end -2.6 2.6) (stroke (width 0.1) (type solid)) (layer "F.Fab"))
	(fp_line (start -2.6 2.6) (end -2.6 -1.6) (stroke (width 0.1) (type solid)) (layer "F.Fab"))
	(fp_line (start -2.6 -1.6) (end -1.6 -2.6) (stroke (width 0.1) (type solid)) (layer "F.Fab"))
	(fp_text user "K" (at -2 0 90) (layer "F.Fab") (effects (font (size 0.6 0.6) (thickness 0.1))))
	(fp_text user "A" (at 2 0 90) (layer "F.Fab") (effects (font (size 0.6 0.6) (thickness 0.1))))
	(fp_text user "${{REFERENCE}}" (at 0 0 0) (layer "F.Fab") (effects (font (size 0.8 0.8) (thickness 0.12))))
	(fp_line (start -2.76 -2.76) (end 2.76 -2.76) (stroke (width 0.12) (type solid)) (layer "F.SilkS"))
	(fp_line (start -2.76 2.76) (end 2.76 2.76) (stroke (width 0.12) (type solid)) (layer "F.SilkS"))
	(fp_line (start -3.2 -2.76) (end -3.2 2.76) (stroke (width 0.12) (type solid)) (layer "F.SilkS"))
	(fp_circle (center -3.3 -3.3) (end -3.1 -3.3) (stroke (width 0.12) (type solid)) (fill solid) (layer "F.SilkS"))
	(fp_rect (start -3.45 -3.6) (end 3.1 3.1) (stroke (width 0.05) (type solid)) (fill none) (layer "F.CrtYd"))
	(pad "2" smd rect (at -2 0) (size 0.8 4.8) (layers "F.Cu" "F.Mask"))
	(pad "3" smd rect (at 0 0) (size 2.2 4.8) (layers "F.Cu" "F.Mask"))
	(pad "1" smd rect (at 2 0) (size 0.8 4.8) (layers "F.Cu" "F.Mask"))
	(pad "" smd rect (at -2 0) (size 0.64 4.04) (layers "F.Paste"))
	(pad "" smd rect (at 0 0) (size 1.76 4.04) (layers "F.Paste"))
	(pad "" smd rect (at 2 0) (size 0.64 4.04) (layers "F.Paste")){vias}
)
'''
open(os.path.join(LIB, 'XFM5050UV.pretty', 'XFM-5050-UV.kicad_mod'), 'w', encoding='utf-8').write(fp)
print('libs written to', LIB)
