# -*- coding: utf-8 -*-
"""Prototype: can ASS render a DJI-style analog gauge?

Needle = a drawn polygon rotated with \\frz around its pivot (\\org).
Ticks = short segments placed by simple trigonometry at build time.
If this frame looks right, the whole dashboard concept is proven, because
digital readouts / bars / title text are all strictly easier than this.
"""
import math
import subprocess
import sys
from pathlib import Path

sys.stdout.reconfigure(encoding="utf-8")
HERE = Path(__file__).parent
FF = r"C:\ai\AUTOMOVIE\app\tools\ffmpeg\bin\ffmpeg.exe"

W, H = 1280, 720
CX, CY, R = 1050, 520, 130          # gauge centre + radius
SWEEP_START, SWEEP_END = 135, 405    # degrees, clockwise: 7 o'clock → 5 o'clock
VMAX = 80                            # km/h full scale
SPEED = 57.6                         # value to display


def polar(cx, cy, r, deg):
    a = math.radians(deg)
    return cx + r * math.cos(a), cy + r * math.sin(a)


ev = []

# outer ring: many short arc segments approximated with thick tick marks
for v in range(0, VMAX + 1, 2):
    deg = SWEEP_START + (SWEEP_END - SWEEP_START) * v / VMAX
    x1, y1 = polar(CX, CY, R, deg)
    x2, y2 = polar(CX, CY, R - (18 if v % 20 == 0 else 9), deg)
    col = "&H4040FF&" if v >= 60 else "&HFFFFFF&"
    ev.append(f"Dialogue: 1,0:00:00.00,0:00:05.00,G,,0,0,0,,"
              f"{{\\an7\\pos(0,0)\\c{col}\\p1}}"
              f"m {x1:.0f} {y1:.0f} l {x2:.0f} {y2:.0f} "
              f"l {x2+3:.0f} {y2+3:.0f} l {x1+3:.0f} {y1+3:.0f}{{\\p0}}")

# scale numbers at major ticks
for v in range(0, VMAX + 1, 20):
    deg = SWEEP_START + (SWEEP_END - SWEEP_START) * v / VMAX
    x, y = polar(CX, CY, R - 38, deg)
    ev.append(f"Dialogue: 1,0:00:00.00,0:00:05.00,Num,,0,0,0,,"
              f"{{\\an5\\pos({x:.0f},{y:.0f})}}{v}")

# needle: drawn pointing straight up from pivot, then rotated with \frz.
# ASS \frz is counter-clockwise; needle drawn at "up" = -90 deg reference.
needle_deg = SWEEP_START + (SWEEP_END - SWEEP_START) * SPEED / VMAX
frz = -(needle_deg - (-90))          # rotation from straight-up to target
ev.append(f"Dialogue: 3,0:00:00.00,0:00:05.00,G,,0,0,0,,"
          f"{{\\an7\\pos(0,0)\\org({CX},{CY})\\frz{frz:.1f}\\c&H3050FF&\\p1}}"
          f"m {CX-5} {CY} l {CX-1} {CY-R+26} l {CX+1} {CY-R+26} l {CX+5} {CY} "
          f"l {CX} {CY+14}{{\\p0}}")
# pivot cap
ev.append(f"Dialogue: 4,0:00:00.00,0:00:05.00,G,,0,0,0,,"
          f"{{\\an7\\pos(0,0)\\c&HE0E0E0&\\p1}}"
          f"m {CX-8} {CY} b {CX-8} {CY-11} {CX+8} {CY-11} {CX+8} {CY} "
          f"b {CX+8} {CY+11} {CX-8} {CY+11} {CX-8} {CY}{{\\p0}}")

# digital readout + unit + title
ev.append(f"Dialogue: 4,0:00:00.00,0:00:05.00,Big,,0,0,0,,"
          f"{{\\an5\\pos({CX},{CY+58})}}{SPEED:.0f}")
ev.append(f"Dialogue: 4,0:00:00.00,0:00:05.00,Unit,,0,0,0,,"
          f"{{\\an5\\pos({CX},{CY+92})}}KM/H")
ev.append(f"Dialogue: 0,0:00:00.00,0:00:05.00,Title,,0,0,0,,"
          f"{{\\an8\\pos({W//2},28)}}濕背約騎 20260801 - 里嶺大橋")

ass = f"""[Script Info]
ScriptType: v4.00+
PlayResX: {W}
PlayResY: {H}
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, OutlineColour, Bold, BorderStyle, Outline, Shadow, Alignment, MarginV, Encoding
Style: G,Arial,20,&H00FFFFFF,&H00000000,0,1,0,0,7,0,1
Style: Num,Microsoft JhengHei,26,&H00E8E8E8,&H00101010,-1,1,2,0,5,0,1
Style: Big,Microsoft JhengHei,64,&H00FFFFFF,&H00101010,-1,1,3,1,5,0,1
Style: Unit,Microsoft JhengHei,22,&H00C0C0C0,&H00101010,-1,1,2,0,5,0,1
Style: Title,Microsoft JhengHei,40,&H005050FF,&H00101010,-1,1,3,1,8,0,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
""" + "\n".join(ev) + "\n"

(HERE / "_gauge.ass").write_text(ass, encoding="utf-8-sig")


def esc(p):
    return str(p).replace("\\", "/").replace(":", r"\:")


# real riding frame as背景, so we judge readability against actual footage
r = subprocess.run(
    [FF, "-v", "error", "-ss", "148",
     "-i", r"C:\ai\AUTOMOVIE\0801.mp4",
     "-vf", f"scale={W}:{H},subtitles=filename='{esc(HERE / '_gauge.ass')}'",
     "-frames:v", "1", "-y", str(HERE / "_gauge.png")],
    capture_output=True, text=True)
print("render:", "OK" if (HERE / "_gauge.png").exists() else r.stderr[-500:])
print(f"事件數: {len(ev)}（單一時刻的一顆錶）")
