import math
import re

import numpy as np


def affine(angle, scale, tx, ty, w, h):
    a = math.radians(angle)
    M = np.array(
        [
            [math.cos(a) * scale, -math.sin(a) * scale, tx],
            [math.sin(a) * scale, math.cos(a) * scale, ty],
        ],
        np.float32,
    )
    cx, cy = w / 2, h / 2
    M[:, 2] += np.dot(M[:, :2], [-cx, -cy]) + [cx, cy]
    return M


def parse_coords_path(coords_path_fn):
    num_pat = r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?"
    line_re = re.compile(
        rf"(\S+)\s+({num_pat})\s+({num_pat})\s+({num_pat})\s+({num_pat})"
    )
    r = {}
    with coords_path_fn.open() as fh:
        for line in fh:
            m = line_re.match(line.strip())
            if not m:
                continue
            fname, ang, scl, tx, ty = m.groups()
            r[fname] = {"ang": ang, "scl": scl, "tx": tx, "ty": ty}
        return r
