#!/usr/bin/env python3
"""
Usage: put this script next to external.css and icons.ttf, then run:

    python3 export_ki_icons.py

Requires: pip install fonttools
"""

import os
import re
from fontTools.ttLib import TTFont
from fontTools.pens.svgPathPen import SVGPathPen

CSS_FILE = "external.css"
TTF_FILE = "icons.ttf"
OUT_DIR = "ki-water-icons"


def parse_css_mapping(css_path):
    """
    Parse lines like:
      .ki-rain:before {content: '\f0f9';}
    and return {codepoint_int: "ki-rain", ...}
    """
    with open(css_path, "r", encoding="utf-8") as f:
        css = f.read()

    pattern = re.compile(
        r"\.ki-([a-z0-9\-]+):before\s*\{\s*content:\s*'\\([0-9a-fA-F]{3,4})';\s*\}",
        re.IGNORECASE,
    )

    mapping = {}
    for name, hexcode in pattern.findall(css):
        cp = int(hexcode, 16)
        mapping[cp] = f"ki-{name}"
    return mapping


def export_icons(css_path=CSS_FILE, ttf_path=TTF_FILE, out_dir=OUT_DIR):
    if not os.path.exists(css_path):
        raise FileNotFoundError(f"CSS file not found: {css_path}")
    if not os.path.exists(ttf_path):
        raise FileNotFoundError(f"TTF file not found: {ttf_path}")

    os.makedirs(out_dir, exist_ok=True)

    # 1) parse CSS
    code_to_name = parse_css_mapping(css_path)
    if not code_to_name:
        raise RuntimeError("No .ki-* icon mappings found in CSS.")

    # 2) load font
    font = TTFont(ttf_path)
    glyph_set = font.getGlyphSet()
    cmap = font.getBestCmap()  # {codepoint_int: glyph_name}

    head = font["head"]
    hhea = font["hhea"]
    units_per_em = head.unitsPerEm
    ascent = hhea.ascent
    _descent = hhea.descent  # usually negative #

    exported = 0
    skipped = []

    for codepoint, icon_name in code_to_name.items():
        glyph_name = cmap.get(codepoint)
        if glyph_name is None:
            skipped.append((icon_name, codepoint))
            continue

        glyph = glyph_set[glyph_name]
        pen = SVGPathPen(glyph_set)
        glyph.draw(pen)
        path_d = pen.getCommands()

        # SVG coordinate fix: font Y goes up, SVG Y goes down.
        # We flip Y and translate so glyph sits within viewBox.
        # Keep SVG simple, valid, and with a style block so QGIS sees default colors.
        # You can still recolor via layer styling (currentColor is not required).
        style_block = """
<style type="text/css">
  .st0{stroke:none;stroke-linejoin:round;stroke-linecap:round;}
</style>""".strip()
        svg = f"""<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
     viewBox="0 0 {units_per_em} {units_per_em}">
  {style_block}
  <g transform="scale(1,-1) translate(0,-{ascent})">
    <path class="st0" d="{path_d}" fill="param(fill) #000000" fill-opacity="param(fill-opacity) 1"/>
  </g>
</svg>
"""

        out_path = os.path.join(out_dir, f"{icon_name}.svg")
        with open(out_path, "w", encoding="utf-8") as f:
            f.write(svg)
        exported += 1

    print(f"Exported {exported} icons to {out_dir}/")

    if skipped:
        print("Skipped (no glyph for codepoint):")
        for name, cp in skipped:
            print(f"  {name}: U+{cp:04X}")


if __name__ == "__main__":
    export_icons()
