# -*- coding: utf-8 -*-
"""Generează identitatea vizuală SC STEEL SRL: logo vectorial (SVG), favicon, PNG-uri, ghid de brand.
Rulează: python3 _build_branding.py  (din folderul branding/)"""
import os, subprocess, json, shutil
from fontTools.ttLib import TTFont
from fontTools.varLib import instancer
from fontTools.pens.svgPathPen import SVGPathPen
from fontTools.pens.boundsPen import BoundsPen

HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(HERE)
for d in ['logo', 'icon', 'favicon', 'png', 'social']:
    os.makedirs(d, exist_ok=True)

INK, BLUE, WHITE, MIST = '#1B1F23', '#1E4D8C', '#FFFFFF', '#EEF1F3'

# ---------------------------------------------------------------- fonturi -> contururi
def load(path, wght):
    f = TTFont(path)
    return instancer.instantiateVariableFont(f, {'wght': wght})

BS = load('fonts/BigShoulders.ttf', 800)
MS = load('fonts/Montserrat.ttf', 500)

def text_path(font, text, size, tracking=0.0):
    """Returnează (path_d, width, ascent, descent) pentru text la mărimea dată, în unități SVG."""
    cmap = font.getBestCmap(); gs = font.getGlyphSet(); hmtx = font['hmtx']
    upm = font['head'].unitsPerEm; k = size / upm
    parts, x = [], 0.0
    for ch in text:
        gname = cmap.get(ord(ch))
        if gname is None:
            x += 0.28 * upm; continue
        pen = SVGPathPen(gs)
        gs[gname].draw(pen)
        d = pen.getCommands()
        if d:
            parts.append('<path transform="translate(%.2f 0) scale(%.5f -%.5f)" d="%s"/>' % (x * k, k, k, d))
        x += hmtx[gname][0] + tracking * upm
    return ''.join(parts), x * k, font['hhea'].ascent * k, -font['hhea'].descent * k

def cap_height(font, size):
    b = BoundsPen(font.getGlyphSet()); font.getGlyphSet()[font.getBestCmap()[ord('H')]].draw(b)
    return b.bounds[3] * size / font['head'].unitsPerEm

# ---------------------------------------------------------------- semnul grafic
# Scară cu balustradă: trepte (linie în trepte), mână curentă (diagonală), trei montanți.
ICON_W, ICON_H = 100, 100
import math
def stadium(x1, y1, x2, y2, w):
    """Linie cu capete rotunjite, ca poligon umplut (funcționează în orice renderer, fără stroke)."""
    r = w / 2.0; dx, dy = x2 - x1, y2 - y1; L = math.hypot(dx, dy); ux, uy = dx / L, dy / L; nx, ny = -uy, ux
    p = lambda x, y: '%.2f %.2f' % (x, y)
    return ('M%s L%s A%.2f %.2f 0 0 0 %s L%s A%.2f %.2f 0 0 0 %s Z' % (
        p(x1 + nx * r, y1 + ny * r), p(x2 + nx * r, y2 + ny * r), r, r, p(x2 - nx * r, y2 - ny * r),
        p(x1 - nx * r, y1 - ny * r), r, r, p(x1 + nx * r, y1 + ny * r)))
def polyline_segments(pts):
    return [(pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1]) for i in range(len(pts) - 1)]
# trepte orizontale + montanți continui (de la mâna curentă până la treapta de sub ei), toate cu aceeași grosime,
# ca îmbinările să fie curate; doar capetele libere sunt rotunjite
TREADS = [(5, 95, 26, 95), (26, 78, 48, 78), (48, 60, 70, 60), (70, 42, 92, 42)]
POSTS = [(26, 47, 26, 95), (48, 29, 48, 78), (70, 11, 70, 60)]
RAIL = (6.4, 63, 72.4, 9)
def shapes(treads, posts, rail, w_lines, w_rail):
    d = ' '.join(stadium(*seg, w_lines) for seg in treads + posts)
    return d + ' ' + stadium(*rail, w_rail)
def icon_paths(color):
    return '<path fill="%s" fill-rule="nonzero" d="%s"/>' % (color, shapes(TREADS, POSTS, RAIL, 9, 10))
ICON_BBOX = (0.5, 3.5, 96.5, 99.5)   # x0 y0 x1 y1 (cu grosimea liniilor)

def svg(w, h, body, bg=None, vb=None):
    vb = vb or (0, 0, w, h)
    bgr = '<rect x="%s" y="%s" width="%s" height="%s" fill="%s"/>' % (vb[0], vb[1], vb[2], vb[3], bg) if bg else ''
    return ('<svg xmlns="http://www.w3.org/2000/svg" viewBox="%s %s %s %s" width="%s" height="%s">' % (vb[0], vb[1], vb[2], vb[3], w, h)
            + bgr + body + '</svg>')

def write(path, content):
    open(path, 'w', encoding='utf-8').write(content)

# ---------------------------------------------------------------- icon (pătrat, decupat strâns)
def icon_svg(color, bg=None, pad=0):
    x0, y0, x1, y1 = ICON_BBOX
    bw, bh = x1 - x0, y1 - y0
    side = max(bw, bh) + 2 * pad
    ox = x0 - (side - bw) / 2; oy = y0 - (side - bh) / 2
    return svg(side, side, icon_paths(color), bg, (round(ox, 2), round(oy, 2), round(side, 2), round(side, 2)))

write('icon/steel-icon-blue.svg', icon_svg(BLUE))
write('icon/steel-icon-dark.svg', icon_svg(INK))
write('icon/steel-icon-white.svg', icon_svg(WHITE))
write('icon/steel-icon-white-on-dark.svg', icon_svg(WHITE, INK, pad=14))
write('icon/steel-icon-white-on-blue.svg', icon_svg(WHITE, BLUE, pad=14))

# ---------------------------------------------------------------- logo orizontal / vertical
NAME, TAG = 'SC STEEL SRL', 'Sighișoara, din 1991'

def lockup(color, tagcolor, orientation='h'):
    name_d, name_w, _, _ = text_path(BS, NAME, 100, tracking=0.01)
    cap = cap_height(BS, 100)
    tag_d, tag_w, _, _ = text_path(MS, TAG, 17)
    tcap = cap_height(MS, 17)
    x0, y0, x1, y1 = ICON_BBOX
    if orientation == 'h':
        ih = cap + tcap + 14           # icon la înălțimea blocului de text
        s = ih / (y1 - y0)
        icon = '<g transform="translate(%.3f 0) scale(%.5f)">%s</g>' % (-x0 * s, s, icon_paths(color))
        tx = (x1 - x0) * s + 24
        name = '<g transform="translate(%.2f %.2f)">%s</g>' % (tx, cap, name_d)
        tag = '<g transform="translate(%.2f %.2f)">%s</g>' % (tx + 1, cap + 14 + tcap, tag_d)
        W, H = tx + max(name_w, tag_w), ih
        return svg(round(W, 1), round(H, 1), icon.replace(color, color) + name + tag), W, H
    else:
        iw = 92; s = iw / (x1 - x0)
        W = max(name_w, iw)
        icon = '<g transform="translate(%.3f 0) scale(%.5f)">%s</g>' % ((W - iw) / 2 - x0 * s, s, icon_paths(color))
        top = (y1 - y0) * s + 26
        name = '<g transform="translate(%.2f %.2f)">%s</g>' % ((W - name_w) / 2, top + cap, name_d)
        tag = '<g transform="translate(%.2f %.2f)">%s</g>' % ((W - tag_w) / 2, top + cap + 14 + tcap, tag_d)
        H = top + cap + 14 + tcap
        return svg(round(W, 1), round(H, 1), icon + name + tag), W, H

def colorize(svg_text, name_color, tag_color, icon_color):
    # textul: nume în name_color, tagline în tag_color; semnul în icon_color
    return svg_text

def build_lockup(fname, orientation, icon_color, name_color, tag_color, bg=None):
    name_d, name_w, _, _ = text_path(BS, NAME, 100, tracking=0.01)
    cap = cap_height(BS, 100)
    tag_d, tag_w, _, _ = text_path(MS, TAG, 17)
    tcap = cap_height(MS, 17)
    x0, y0, x1, y1 = ICON_BBOX
    if orientation == 'h':
        ih = cap + tcap + 14; s = ih / (y1 - y0)
        icon = '<g transform="translate(%.3f %.3f) scale(%.5f)">%s</g>' % (-x0 * s, -y0 * s, s, icon_paths(icon_color))
        tx = (x1 - x0) * s + 24
        name = '<g fill="%s" transform="translate(%.2f %.2f)">%s</g>' % (name_color, tx, cap, name_d)
        tag = '<g fill="%s" transform="translate(%.2f %.2f)">%s</g>' % (tag_color, tx + 1, cap + 14 + tcap, tag_d)
        W, H = tx + max(name_w, tag_w), ih + 0.24 * 17
    else:
        iw = 130; s = iw / (x1 - x0); W = max(name_w, iw)
        icon = '<g transform="translate(%.3f %.3f) scale(%.5f)">%s</g>' % ((W - iw) / 2 - x0 * s, -y0 * s, s, icon_paths(icon_color))
        top = (y1 - y0) * s + 26
        name = '<g fill="%s" transform="translate(%.2f %.2f)">%s</g>' % (name_color, (W - name_w) / 2, top + cap, name_d)
        tag = '<g fill="%s" transform="translate(%.2f %.2f)">%s</g>' % (tag_color, (W - tag_w) / 2, top + cap + 14 + tcap, tag_d)
        H = top + cap + 14 + tcap + 0.24 * 17
    pad = 0 if bg is None else 0.12 * H
    vb = (-pad, -pad, W + 2 * pad, H + 2 * pad)
    out = svg(round(vb[2], 1), round(vb[3], 1), icon + name + tag, bg, tuple(round(v, 2) for v in vb))
    write(fname, out)
    return out

# pentru fundal deschis (culori de brand) / fundal închis (alb) / monocrom
build_lockup('logo/steel-logo-horizontal-color.svg', 'h', BLUE, INK, '#6F7982')
build_lockup('logo/steel-logo-horizontal-dark.svg', 'h', INK, INK, INK)
build_lockup('logo/steel-logo-horizontal-white.svg', 'h', WHITE, WHITE, WHITE)
build_lockup('logo/steel-logo-horizontal-white-on-dark.svg', 'h', WHITE, WHITE, '#B7C0C9', bg=INK)
build_lockup('logo/steel-logo-vertical-color.svg', 'v', BLUE, INK, '#6F7982')
build_lockup('logo/steel-logo-vertical-dark.svg', 'v', INK, INK, INK)
build_lockup('logo/steel-logo-vertical-white.svg', 'v', WHITE, WHITE, WHITE)
build_lockup('logo/steel-logo-vertical-white-on-dark.svg', 'v', WHITE, WHITE, '#B7C0C9', bg=INK)

# ---------------------------------------------------------------- favicon
# la 16–32 px liniile subțiri dispar: variantă simplificată, mai groasă, pe fond albastru cu colțuri rotunjite
def favicon_svg(size_hint=None):
    body = ('<rect width="100" height="100" rx="18" fill="%s"/>' % BLUE +
            '<path fill="#FFFFFF" d="%s"/>' % shapes([(14, 86, 33, 86), (33, 68, 52, 68), (52, 50, 71, 50), (71, 32, 88, 32)],
                                                     [(33, 45, 33, 86), (52, 28, 52, 68), (71, 12, 71, 50)], (16, 58, 72, 12), 11, 12))
    return svg(100, 100, body)
write('favicon/favicon.svg', favicon_svg())

# ---------------------------------------------------------------- raster (PNG / ICO) cu ImageMagick
def rasterize(src, dst, width=None, height=None, density=None, bg='none'):
    cmd = ['magick', '-background', bg]
    if density: cmd += ['-density', str(density)]
    cmd += [src]
    if width or height: cmd += ['-resize', '%sx%s' % (width or '', height or '')]
    cmd += ['-strip', dst]
    subprocess.run(cmd, check=True)

rasterize('favicon/favicon.svg', 'favicon/favicon-16.png', 16, 16, density=600)
rasterize('favicon/favicon.svg', 'favicon/favicon-32.png', 32, 32, density=600)
rasterize('favicon/favicon.svg', 'favicon/favicon-48.png', 48, 48, density=600)
rasterize('favicon/favicon.svg', 'favicon/apple-touch-icon-180.png', 180, 180, density=600)
rasterize('favicon/favicon.svg', 'favicon/android-chrome-192.png', 192, 192, density=600)
rasterize('favicon/favicon.svg', 'favicon/android-chrome-512.png', 512, 512, density=600)
subprocess.run(['magick', 'favicon/favicon-16.png', 'favicon/favicon-32.png', 'favicon/favicon-48.png', 'favicon/favicon.ico'], check=True)
write('favicon/site.webmanifest', json.dumps({"name": "SC STEEL SRL", "short_name": "STEEL", "icons": [
    {"src": "/android-chrome-192.png", "sizes": "192x192", "type": "image/png"},
    {"src": "/android-chrome-512.png", "sizes": "512x512", "type": "image/png"}],
    "theme_color": BLUE, "background_color": "#FFFFFF", "display": "standalone"}, indent=2))
write('favicon/head-snippet.html', '''<!-- de pus în <head> pe site -->
<link rel="icon" href="/favicon.ico" sizes="48x48">
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/apple-touch-icon-180.png">
<link rel="manifest" href="/site.webmanifest">
<meta name="theme-color" content="%s">
''' % BLUE)

for name in ['horizontal-color', 'horizontal-dark', 'horizontal-white', 'vertical-color', 'vertical-dark', 'vertical-white']:
    rasterize('logo/steel-logo-%s.svg' % name, 'png/steel-logo-%s-2000px.png' % name, 2000, None, density=1200)
for name in ['blue', 'dark', 'white']:
    rasterize('icon/steel-icon-%s.svg' % name, 'png/steel-icon-%s-1024px.png' % name, 1024, 1024, density=1200)

# ---------------------------------------------------------------- social media
def social(fname, W, H, bg, logo_svg, logo_w):
    # logo centrat pe fundal
    lw = logo_w; import re
    vb = re.search(r'viewBox="([^"]+)"', logo_svg).group(1).split()
    vw, vh = float(vb[2]), float(vb[3]); s = lw / vw; lh = vh * s
    inner = re.sub(r'^<svg[^>]*>|</svg>$', '', logo_svg)
    inner = re.sub(r'<rect x="[^"]*" y="[^"]*" width="[^"]*" height="[^"]*" fill="#1B1F23"/>', '', inner)
    body = '<rect width="%d" height="%d" fill="%s"/>' % (W, H, bg) + '<g transform="translate(%.1f %.1f) scale(%.5f) translate(%s %s)">%s</g>' % ((W - lw) / 2, (H - lh) / 2, s, -float(vb[0]), -float(vb[1]), inner)
    out = svg(W, H, body); write(fname + '.svg', out); rasterize(fname + '.svg', fname + '.png', W, H, density=300, bg=bg)

social('social/avatar-1080', 1080, 1080, BLUE, open('icon/steel-icon-white.svg').read(), 560)
social('social/avatar-dark-1080', 1080, 1080, INK, open('logo/steel-logo-vertical-white.svg').read(), 700)
social('social/og-image-1200x630', 1200, 630, INK, open('logo/steel-logo-horizontal-white.svg').read(), 760)
social('social/facebook-cover-1640x624', 1640, 624, MIST, open('logo/steel-logo-horizontal-color.svg').read(), 820)
social('social/linkedin-cover-1584x396', 1584, 396, INK, open('logo/steel-logo-horizontal-white.svg').read(), 640)

print('done')
