import cv2

def calcula_escala_font(texto, font, thickness_base, ancho_frame, margin):
    # Medimos a escala 1.0
    (w_texto, _), _ = cv2.getTextSize(texto, font, 1.0, thickness_base)
    # Ajustamos la escala para que el texto + 2*margin entre en el frame
    escala = (ancho_frame - 1*margin) / w_texto
    return escala

# Parámetros
video_path   = "./video.mp4"
cap          = cv2.VideoCapture(video_path)
fps          = cap.get(cv2.CAP_PROP_FPS)
w            = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h            = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc       = cv2.VideoWriter_fourcc(*"mp4v")
out          = cv2.VideoWriter("video_con_margen.mp4", fourcc, fps, (w, h))

texto            = "Hola Hola"
font             = cv2.FONT_HERSHEY_SIMPLEX
thickness_base   = 2

# 1) Espacio al borde del vídeo
margin_video     = 100  

# 2) Padding interno del rectángulo al texto
pad_text         = 20   

# Calcula escala y grosor
fontScale = calcula_escala_font(texto, font, thickness_base, w, margin_video)
thickness = max(1, int(thickness_base * fontScale))

# Recalculamos tamaño del texto y coordenadas
(text_w, text_h), baseline = cv2.getTextSize(texto, font, fontScale, thickness)
# Centrado (toma en cuenta sólo el ancho disponible: w - 2*margin_video)
x = margin_video + ((w - 2*margin_video) - text_w) // 2
y = (h + text_h) // 2

while True:
    ret, frame = cap.read()
    if not ret: break

    t = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000.0
    if 0.0 <= t <= 5.0:
        # Fondo negro (usa pad_text para el interior)
        tl = (x - pad_text, y - text_h - baseline - pad_text)
        br = (x + text_w + pad_text, y + baseline + pad_text)
        cv2.rectangle(frame, tl, br, (0,0,0), cv2.FILLED)

        # Texto centrado dentro del rectángulo
        cv2.putText(frame, texto, (x, y),
                    font, fontScale, (255,255,255),
                    thickness, cv2.LINE_AA)

    out.write(frame)

cap.release()
out.release()
print("✓ Vídeo generado como video_con_margen.mp4")