#!/usr/bin/env python3
# Verificacao manual (nao comitar como teste oficial): sobe o app em modo harness, importa um
# arquivo real com audio+video, adiciona na timeline, da play, e tira screenshot pra confirmar
# visualmente se o preview renderiza (nao fica preto) durante o play de verdade.
import json, socket, subprocess, sys, time, os, re, glob

BIN = sys.argv[1]
MEDIA_DIR = sys.argv[2]
PORT = 8766
env = dict(os.environ, VIDEOTASK_HARNESS_PORT=str(PORT))
proc = subprocess.Popen([BIN], env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)

port = None
t0 = time.time()
while time.time() - t0 < 15:
    line = proc.stdout.readline()
    if not line:
        if proc.poll() is not None:
            print("APP MORREU antes de anunciar."); sys.exit(1)
        continue
    print("  [app]", line.rstrip())
    m = re.search(r"VIDEOTASK_HARNESS_LISTENING (\d+)", line)
    if m:
        port = int(m.group(1)); break
if not port:
    print("FALHA: app nao anunciou porta"); proc.terminate(); sys.exit(1)

s = socket.create_connection(("127.0.0.1", port), timeout=5)
f = s.makefile("rwb", buffering=0)
_id = [0]
def call(method, params=None):
    _id[0] += 1
    msg = {"id": _id[0], "method": method}
    if params is not None: msg["params"] = params
    f.write((json.dumps(msg) + "\n").encode())
    resp = json.loads(f.readline().decode())
    return resp

print("\n== importFolder =="); r = call("drive", {"action":"importFolder","path":MEDIA_DIR}); print(r)

item = None
for _ in range(50):
    st = call("dump_state")["result"]
    items = st["mediaLibrary"]["items"]
    if items and items[0]["status"] == "ready":
        item = items[0]; break
    time.sleep(0.2)
print("item:", item)
if not item:
    print("FALHA: item nunca ficou ready"); proc.terminate(); sys.exit(1)

st = call("dump_state")["result"]
video_track = next((t for t in st["tracks"] if t["kind"] == "video"), None)
print("video_track:", video_track)
if not video_track:
    print("FALHA: sem track de video"); proc.terminate(); sys.exit(1)

print("\n== addToTimeline =="); r = call("drive", {"action":"addToTimeline","mediaItemID":item["id"],"trackID":video_track["id"]}); print(r)

st = call("dump_state")["result"]
print("tracks apos add:", [(t["kind"], [(c["position"], c["duration"]) for c in t["clips"]]) for t in st["tracks"]])

print("\n== play =="); r = call("drive", {"action":"play"}); print(r)
time.sleep(1.0)
st = call("dump_state")["result"]
print("isPlaying:", st["isPlaying"], "playheadFrame:", st["playheadFrame"])

# Screenshot da janela do app (procura pelo titulo/processo).
shot_path = "/tmp/vt_harness_shot.png"
subprocess.run(["screencapture", "-x", "-o", shot_path], check=False)
print("screenshot salvo em", shot_path)

time.sleep(0.5)
st2 = call("dump_state")["result"]
print("isPlaying2:", st2["isPlaying"], "playheadFrame2:", st2["playheadFrame"])

call("drive", {"action":"pause"})
proc.terminate()
