File size: 156,439 Bytes
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b72059
7af396c
 
 
 
 
 
 
c09ac99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
 
 
7af396c
 
b26588d
 
 
ad51582
 
 
 
 
 
 
 
923a92d
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
bbdd295
 
 
 
0dc0bc5
bbdd295
 
7af396c
 
 
 
 
 
 
 
 
c09ac99
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
0dc0bc5
dc89e4b
7af396c
 
0dc0bc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c09ac99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
0dc0bc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc89e4b
0dc0bc5
dc89e4b
0dc0bc5
 
 
 
dc89e4b
 
 
 
 
 
0dc0bc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc89e4b
 
 
 
 
 
 
0dc0bc5
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
c09ac99
 
7af396c
c09ac99
 
 
 
7af396c
 
 
 
0dc0bc5
c09ac99
 
 
 
 
 
 
 
 
 
7af396c
 
 
0dc0bc5
c09ac99
0dc0bc5
c09ac99
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
49cca11
 
 
 
 
 
 
 
7af396c
 
0b72059
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad51582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
923a92d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c09ac99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b72059
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49cca11
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
49cca11
 
 
 
 
 
 
 
7af396c
 
 
 
bbdd295
 
 
 
 
 
 
7af396c
 
 
 
 
 
bbdd295
 
7af396c
 
 
 
 
 
 
49cca11
7af396c
 
 
 
 
 
 
49cca11
7af396c
 
 
49cca11
7af396c
 
 
 
 
 
 
49cca11
 
 
7af396c
49cca11
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c09ac99
7af396c
c09ac99
 
 
7af396c
c09ac99
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c09ac99
7af396c
 
 
 
c09ac99
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49cca11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
c09ac99
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbdd295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
49cca11
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dc0bc5
bbdd295
 
0dc0bc5
bbdd295
 
 
 
 
 
 
 
 
 
 
 
0dc0bc5
bbdd295
 
 
 
 
 
 
 
 
 
 
 
 
0dc0bc5
7af396c
 
c09ac99
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49cca11
7af396c
 
c09ac99
 
 
 
 
 
 
 
7af396c
c09ac99
7af396c
c09ac99
 
7af396c
c09ac99
7af396c
c09ac99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
ac03051
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
7af396c
 
 
 
 
b26588d
923a92d
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
7af396c
 
 
 
 
 
 
b26588d
 
7af396c
923a92d
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
ad51582
 
 
7af396c
ad51582
 
 
 
 
c09ac99
ad51582
 
 
c09ac99
ad51582
c09ac99
7af396c
 
 
 
ad51582
 
c09ac99
7af396c
 
 
 
 
 
 
883fcaa
 
 
 
 
 
 
 
 
 
 
 
84e5364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d8f618
 
84e5364
 
 
0d8f618
 
84e5364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883fcaa
 
 
 
f0f19dc
883fcaa
f0f19dc
883fcaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad51582
 
 
7af396c
 
ad51582
 
 
c09ac99
ad51582
 
 
c09ac99
ad51582
c09ac99
7af396c
 
 
ad51582
 
c09ac99
7af396c
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
 
 
 
 
 
 
 
 
 
6ae0b71
 
 
 
 
 
 
 
 
 
 
 
 
0cc810d
 
 
7af396c
 
 
 
 
 
6ae0b71
 
 
 
 
 
 
 
 
 
7af396c
 
6ae0b71
923a92d
 
 
 
 
7af396c
 
0cc810d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ae0b71
 
 
 
 
0cc810d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
923a92d
 
 
 
 
b26588d
 
7af396c
 
6ae0b71
7af396c
 
b26588d
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
6ae0b71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
6ae0b71
b26588d
 
f0f19dc
 
883fcaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0f19dc
 
883fcaa
f0f19dc
 
 
 
 
 
 
 
 
 
 
 
 
 
883fcaa
f0f19dc
 
 
 
883fcaa
 
84e5364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883fcaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84e5364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
7af396c
 
 
b26588d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cc810d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50f1ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da4b9f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cc810d
 
 
 
50f1ec0
da4b9f5
0cc810d
 
 
b26588d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50f1ec0
 
 
 
0cc810d
 
 
 
 
 
 
 
 
 
 
 
 
 
50f1ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cc810d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
 
 
 
 
 
 
 
 
 
0cc810d
 
 
b26588d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cc810d
b26588d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cc810d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da4b9f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cc810d
 
da4b9f5
50f1ec0
 
 
da4b9f5
 
 
 
 
0cc810d
 
 
 
 
50f1ec0
da4b9f5
0cc810d
 
 
b26588d
 
 
6ae0b71
 
 
0cc810d
 
 
6ae0b71
 
b26588d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cc810d
 
da4b9f5
50f1ec0
 
 
da4b9f5
 
 
 
 
0cc810d
 
 
 
 
50f1ec0
da4b9f5
0cc810d
 
 
b26588d
 
 
 
6ae0b71
 
 
0cc810d
 
 
6ae0b71
 
b26588d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3723f9
7af396c
c3723f9
 
 
92e7937
c3723f9
92e7937
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
 
 
7af396c
 
 
b26588d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
6ae0b71
b26588d
7af396c
 
b26588d
 
6ae0b71
b26588d
 
 
6ae0b71
b26588d
7af396c
 
6ae0b71
b26588d
7af396c
 
 
6ae0b71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
b26588d
 
7af396c
6ae0b71
 
 
 
 
 
b26588d
 
6ae0b71
 
 
b26588d
7af396c
 
 
5bbf51d
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
 
 
 
5bbf51d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
 
 
7af396c
b26588d
 
92e7937
b26588d
92e7937
 
 
 
 
 
 
 
 
b26588d
 
92e7937
 
 
b26588d
 
 
92e7937
b26588d
7af396c
 
 
 
 
 
 
 
 
 
5bbf51d
 
7af396c
5bbf51d
b26588d
7af396c
 
 
 
 
 
5bbf51d
7af396c
 
 
 
 
 
b26588d
5bbf51d
 
 
 
 
 
 
7af396c
5bbf51d
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
b26588d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bbf51d
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92e7937
 
 
7af396c
92e7937
 
 
7af396c
 
92e7937
 
 
7af396c
 
92e7937
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
c3723f9
 
 
 
7af396c
 
c3723f9
 
 
5bbf51d
 
92e7937
 
 
 
 
5bbf51d
 
c3723f9
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bbf51d
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3723f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffbb4de
 
7af396c
 
ffbb4de
 
 
 
 
 
 
 
 
 
 
7af396c
 
ffbb4de
 
 
 
 
 
 
 
 
0b72059
ffbb4de
7af396c
ffbb4de
0b72059
ffbb4de
 
 
 
 
 
 
 
 
 
 
0b72059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffbb4de
 
 
 
 
 
 
0b72059
ffbb4de
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
923a92d
 
0cc810d
923a92d
7af396c
 
 
 
 
 
 
 
 
 
 
ad51582
49cca11
923a92d
 
ad51582
 
c09ac99
 
ad51582
c09ac99
 
 
7af396c
 
 
 
 
49cca11
c09ac99
7af396c
c09ac99
7af396c
 
 
 
ad51582
7af396c
c09ac99
7af396c
 
 
 
 
 
 
ffbb4de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883fcaa
 
 
 
 
84e5364
883fcaa
 
 
ffbb4de
 
 
b38204f
 
 
 
 
 
 
 
 
ffbb4de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad51582
 
 
 
 
 
 
c09ac99
ad51582
 
 
c09ac99
ad51582
c09ac99
7af396c
 
 
ad51582
 
c09ac99
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b72059
 
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbdd295
7af396c
 
 
 
 
 
 
 
 
 
bbdd295
 
 
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac03051
7af396c
c09ac99
 
 
 
7af396c
c09ac99
7af396c
c09ac99
7af396c
 
 
 
 
 
 
 
 
 
 
49cca11
 
7af396c
49cca11
7af396c
 
49cca11
 
7af396c
49cca11
 
 
 
7af396c
49cca11
7af396c
 
 
 
 
49cca11
7af396c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
#!/usr/bin/env python3
"""
clip_workflow.py — Automated YouTube Livestream Clipper for Peñarol Fan Show

Usage — canal (último stream):
    python clip_workflow.py --channel "https://www.youtube.com/@TuCanal"

Usage — video directo:
    python clip_workflow.py --video "https://www.youtube.com/watch?v=VIDEO_ID"
    python clip_workflow.py --video "https://www.youtube.com/watch?v=VIDEO_ID" --clips 5

Requirements: see requirements.txt + setup.sh
"""

import argparse
import contextlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

import anthropic


# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
# Use ffmpeg-full (includes libass/freetype for subtitle burning)
FFMPEG_BIN = "/opt/homebrew/opt/ffmpeg-full/bin/ffmpeg"
YTDLP_BIN = Path(sys.executable).with_name("yt-dlp")

# Quality settings for encodes
# CRF: lower = better quality / larger file. 18 = visually lossless.
VIDEO_CRF     = "18"
VIDEO_PRESET  = "slow"   # slow = better compression at same quality
AUDIO_BITRATE = "320k"

# Subtle finishing filters. They are intentionally conservative: enough to make
# livestream clips feel less flat without changing skin tones or making the
# logo/subtitles look processed. Filters run before branding and subtitles.
VIDEO_POLISH_FILTER = (
    "eq=contrast=1.035:saturation=1.03:brightness=0.003,"
    "unsharp=5:5:0.28:3:3:0.08"
)
AUDIO_POLISH_FILTER = (
    "aformat=sample_fmts=fltp:channel_layouts=stereo,"
    "loudnorm=I=-16:LRA=11:TP=-1.5,"
    "acompressor=threshold=-18dB:ratio=2.2:attack=8:release=160,"
    "alimiter=limit=0.95,"
    "aresample=async=1:first_pts=0"
)
TARGET_MAX_CLIP_DURATION = 60.0
ABSOLUTE_MAX_CLIP_DURATION = 65.0
END_PAD_SECONDS = 0.25

# Split-panel livestream frames include a thin black/program border at the very
# top. Panel crops should start a little lower so social clips show only the
# active panel. Single-camera close-ups use a separate y anchor because their
# bottom broadcast border is more visible than the top edge.
VERTICAL_TOP_GUARD_RATIO = 0.04
PANEL_CROP_HEIGHT_RATIO = 0.88
TALKNET_DIR = Path(__file__).resolve().parent / "experiments" / "TalkNet-ASD"
TALKNET_MODEL_PATH = TALKNET_DIR / "pretrain_TalkSet.model"
_TALKNET_MODEL = None
ASSETS_DIR = Path(__file__).resolve().parent / "assets"
PYD_LOGO_PATH = ASSETS_DIR / "pyd-logo.png"
PYD_LOGO_VERTICAL_WIDTH = 210
PYD_LOGO_HORIZONTAL_WIDTH = 230
PYD_LOGO_VERTICAL_MARGIN_X = 38
PYD_LOGO_VERTICAL_MARGIN_Y = 42
PYD_LOGO_HORIZONTAL_MARGIN_X = 42
PYD_LOGO_HORIZONTAL_MARGIN_Y = 34
SOURCE_LOGO_RIGHT_X = 320
SOURCE_LOGO_CLEAR_Y = 130
SOURCE_LOGO_BOTTOM_GUARD_RATIO = 0.035

# YouTube increasingly hides high-quality formats behind PO-token/SABR flows.
# When the local bgutil provider is available, use it automatically so recently
# finished lives expose 720p/1080p formats instead of only the low 360p stream.
NODE22_BIN = Path("/opt/homebrew/opt/node@22/bin/node")
BGUTIL_SERVER_HOME = Path("/Users/emiliarodrig/bgutil-ytdlp-pot-provider/server")
YOUTUBE_HQ_FORMAT = (
    "bv*[height<=1080][vcodec^=avc1]+ba[ext=m4a]/"
    "bv*[height<=1080]+ba/"
    "bv*+ba/"
    "best[ext=mp4]/best"
)
WHISPER_INITIAL_PROMPT = (
    "Programa uruguayo de fútbol de Padre y Decano sobre Peñarol. "
    "Vocabulario frecuente: Peñarol, Peñaroleando, Carbonero, aurinegro, "
    "Copa Libertadores, Campeón del Siglo, Ruglio, Aguirre, Nacho, Freddy, "
    "Ignacio Ruglio, abono, abonos, socios, butacas, palcos, entradas, "
    "Manyas, clásico, Nacional, Uruguay, CONMEBOL."
)

# ---------------------------------------------------------------------------
# Subtitle text normalization
# ---------------------------------------------------------------------------
# Known corrections applied automatically at subtitle-generation time.
# Keys are regex patterns (case-insensitive), values are the correct replacement.
# Extend this dict when recurring Whisper errors are found for this show.
SUBTITLE_CORRECTIONS: dict[str, str] = {
    r"\bpe[nñ]arol\b":     "Peñarol",
    r"\bpadre\s+y\s+decano\b": "Padre y Decano",
    r"\bpydtv\b":           "PyDTV",
    r"\bpyd\b":             "PyD",
    r"\bdanubio\b":         "Danubio",
    r"\buruguay\b":         "Uruguay",
    r"\buruguayo\b":        "Uruguayo",
    r"\buruguaya\b":        "Uruguaya",
    r"\buruguayos\b":       "Uruguayos",
    r"\buruguayas\b":       "Uruguayas",
    r"\baguirre\b":         "Aguirre",
    r"\bfern[aá]ndez\b":   "Fernández",
    r"\bmonumental\b":      "Monumental",
    r"\bcentenario\b":      "Centenario",
    r"\bparque central\b":  "Parque Central",
    r"\bmercosur\b":        "Mercosur",
    r"\bsud[aá]merica\b":  "Sudamérica",
    r"\bruglio\b":          "Ruglio",
    r"\bsarro\b":           "Cerro",
}

RUGLIO_CONTEXT_RE = re.compile(
    r"\b("
    r"ignacio|nacho|presidente|dirigente|directiva|directivo|consejo|"
    r"comisi[oó]n|club|pe[nñ]arol|carbonero|aurinegro|ruglio"
    r")\b",
    flags=re.IGNORECASE,
)
ABONO_CONTEXT_RE = re.compile(
    r"\b("
    r"abono|abonos|abonado|abonados|socio|socios|butaca|butacas|palco|palcos|"
    r"entrada|entradas|precio|precios|tribuna|estadio|cancha|campe[oó]n|siglo|"
    r"temporada|cuota|cuotas|pagar|pago|sacar|sac[oó]|sacado|saque|"
    r"llenar|llena|local|partido"
    r")\b",
    flags=re.IGNORECASE,
)

SUBTITLE_FILLER_WORDS = {
    "ah",
    "eh",
    "ehh",
    "em",
    "mmm",
    "um",
    "este",
    "ta",
}


def _plain_subtitle_word(text: str) -> str:
    return re.sub(r"[^0-9A-Za-zÁÉÍÓÚÜÑáéíóúüñ]+", "", text).lower()


def _case_like(source: str, replacement: str) -> str:
    if source.isupper():
        return replacement.upper()
    if source[:1].isupper():
        return replacement[:1].upper() + replacement[1:]
    return replacement


def _replace_bono_as_abono(match: re.Match) -> str:
    word = match.group(0)
    replacement = "abonos" if _plain_subtitle_word(word).endswith("s") else "abono"
    return _case_like(word, replacement)


def _replace_bono_phrase(match: re.Match) -> str:
    phrase = match.group(0)
    plural = _plain_subtitle_word(match.group("noun")).endswith("s")
    replacement = "los abonos" if plural else "el abono"
    if phrase.isupper():
        return replacement.upper()
    if phrase[:1].isupper():
        return replacement[:1].upper() + replacement[1:]
    return replacement


def apply_contextual_subtitle_corrections(text: str, context: str = "") -> str:
    """Fix recurrent Whisper confusions only when the surrounding text supports it."""
    context_text = f"{context} {text}".strip()
    if re.search(r"\b(?:rubio|rublio|rublo)\b", text, flags=re.IGNORECASE) and RUGLIO_CONTEXT_RE.search(context_text):
        text = re.sub(
            r"\b(?:rubio|rublio|rublo)\b",
            lambda m: _case_like(m.group(0), "Ruglio"),
            text,
            flags=re.IGNORECASE,
        )
    text = re.sub(
        r"\b(?:iba\s+irre|eva\s+aguirre)\b",
        lambda m: _case_like(m.group(0), "Diego Aguirre"),
        text,
        flags=re.IGNORECASE,
    )
    if re.search(r"\bbonos?\b", text, flags=re.IGNORECASE) and ABONO_CONTEXT_RE.search(context_text):
        text = re.sub(
            r"\b(?:la|las)\s+(?P<noun>bonos?)\b",
            _replace_bono_phrase,
            text,
            flags=re.IGNORECASE,
        )
        text = re.sub(r"\bbonos?\b", _replace_bono_as_abono, text, flags=re.IGNORECASE)
    return text


def normalize_subtitle_word_sequence(word_items: list[dict]) -> None:
    """Polish grammar after per-word contextual corrections."""
    for idx, item in enumerate(word_items):
        plain = _plain_subtitle_word(str(item.get("word", "")))
        if idx > 0 and plain in {"irre", "aguirre"}:
            prev = word_items[idx - 1]
            prev_plain = _plain_subtitle_word(str(prev.get("word", "")))
            if prev_plain in {"iba", "eva"}:
                prev["word"] = _case_like(str(prev.get("word", "")), "Diego")
                item["word"] = _case_like(str(item.get("word", "")), "Aguirre")
                continue
        if plain not in {"abono", "abonos"} or idx == 0:
            continue
        prev = word_items[idx - 1]
        prev_plain = _plain_subtitle_word(str(prev.get("word", "")))
        if plain == "abono" and prev_plain in {"la", "las"}:
            prev["word"] = _case_like(str(prev.get("word", "")), "el")
        elif plain == "abonos" and prev_plain in {"la", "las", "el"}:
            prev["word"] = _case_like(str(prev.get("word", "")), "los")


def normalize_subtitle_text(text: str, context: str = "") -> str:
    """
    Normalize a subtitle line:
      - Applies known proper-noun corrections (Peñarol, Uruguay, player names…)
      - Removes transcription/control artifacts that look ugly when burned in
      - Drops standalone filler words only when they are not meaningful content
    """
    text = str(text)
    text = re.sub(r"(?i)(?:\\n|/n)", " ", text)
    text = text.replace("\n", " ").replace("\r", " ")
    text = re.sub(r"\s+", " ", text).strip()
    if not text:
        return text
    for pattern, replacement in SUBTITLE_CORRECTIONS.items():
        text = re.sub(pattern, replacement, text, flags=re.IGNORECASE)
    text = apply_contextual_subtitle_corrections(text, context)
    text = re.sub(r"\s+([,.;:!?])", r"\1", text)
    text = re.sub(r"([¿¡])\s+", r"\1", text)
    text = re.sub(r"\s{2,}", " ", text).strip()

    words = text.split()
    if words and all(_plain_subtitle_word(word) in SUBTITLE_FILLER_WORDS for word in words):
        return ""
    while len(words) > 1 and _plain_subtitle_word(words[0]) in SUBTITLE_FILLER_WORDS:
        words.pop(0)
    text = " ".join(words).strip()
    return text


def subtitle_display_text(text: str, context: str = "") -> str:
    """Return final text as it should appear in burned social subtitles."""
    return normalize_subtitle_text(text, context=context).upper()


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def run(cmd: list[str], check: bool = True) -> subprocess.CompletedProcess:
    """Run a shell command, print it, and return the result."""
    print(f"    $ {' '.join(str(c) for c in cmd)}")
    result = subprocess.run(cmd, capture_output=True, text=True, check=False)
    if check and result.returncode != 0:
        print(f"[ERROR] Command failed:\n{result.stderr}", file=sys.stderr)
        sys.exit(1)
    return result


def write_text_if_changed(path: Path, text: str) -> bool:
    """Write text only when content changed; returns whether the file changed."""
    if path.exists() and path.read_text(encoding="utf-8") == text:
        return False
    path.write_text(text, encoding="utf-8")
    return True


def ytdlp_hq_cmd() -> list[str]:
    """Return yt-dlp command prefix with local PO-token support when available."""
    cmd = [str(YTDLP_BIN) if YTDLP_BIN.exists() else "yt-dlp"]
    bgutil_script = BGUTIL_SERVER_HOME / "build" / "generate_once.js"
    if NODE22_BIN.exists() and bgutil_script.exists():
        cmd.extend([
            "--js-runtimes", f"node:{NODE22_BIN}",
            # Disable Deno for the bgutil script provider: on this machine it
            # may spend minutes downloading deps and timeout before Node runs.
            "--js-runtimes", "deno:/nonexistent-deno",
            "--remote-components", "ejs:github",
            "--extractor-args",
            "youtube:player_client=mweb,web_safari,web,web_embedded,ios;formats=missing_pot",
            "--extractor-args",
            f"youtubepot-bgutilscript:server_home={BGUTIL_SERVER_HOME}",
        ])
    return cmd


def srt_time(seconds: float) -> str:
    """Float seconds → SRT timestamp format HH:MM:SS,mmm"""
    h = int(seconds // 3600)
    m = int((seconds % 3600) // 60)
    s = int(seconds % 60)
    ms = int((seconds % 1) * 1000)
    return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"


def safe_name(text: str, max_len: int = 50) -> str:
    """Convert arbitrary text to a safe filesystem name."""
    cleaned = re.sub(r"[^\w\s-]", "", text, flags=re.UNICODE)
    return cleaned.strip().replace(" ", "_")[:max_len]


def pyd_logo_path() -> Path | None:
    """Return the PyDTV logo asset when available."""
    configured = os.environ.get("PYD_LOGO_PATH")
    path = Path(configured).expanduser() if configured else PYD_LOGO_PATH
    return path if path.exists() else None


def add_pyd_logo_filter(
    parts: list[str],
    base_label: str,
    logo_input_index: int,
    output_label: str,
    *,
    vertical: bool = True,
) -> str:
    """Append ffmpeg filters that overlay the PyDTV logo on a finished frame."""
    width = PYD_LOGO_VERTICAL_WIDTH if vertical else PYD_LOGO_HORIZONTAL_WIDTH
    margin_x = PYD_LOGO_VERTICAL_MARGIN_X if vertical else PYD_LOGO_HORIZONTAL_MARGIN_X
    margin_y = PYD_LOGO_VERTICAL_MARGIN_Y if vertical else PYD_LOGO_HORIZONTAL_MARGIN_Y
    logo_label = f"{output_label}_logo"
    parts.append(f"[{logo_input_index}:v]scale={width}:-1:flags=lanczos[{logo_label}]")
    parts.append(
        f"[{base_label}][{logo_label}]overlay={margin_x}:{margin_y}:format=auto[{output_label}]"
    )
    return output_label


def avoid_source_logo_crop(crop: dict, src_w: int, src_h: int) -> dict:
    """Move/trim crops so the broadcast PyDTV logo is outside the frame."""
    out = dict(crop)
    x = int(out.get("x", 0))
    y = int(out.get("y", 0))
    w = int(out.get("w", src_w))
    h = int(out.get("h", src_h))
    if x > SOURCE_LOGO_RIGHT_X or y >= SOURCE_LOGO_CLEAR_Y:
        return out

    target_y = min(SOURCE_LOGO_CLEAR_Y, max(0, src_h - 1))
    bottom_guard = max(0, int(src_h * SOURCE_LOGO_BOTTOM_GUARD_RATIO))
    max_h = max(1, src_h - target_y - bottom_guard)
    if h > max_h:
        center_x = x + w / 2
        h = max_h
        w = min(src_w, max(1, int(h * 9 / 16)))
        x = max(0, min(int(center_x - w / 2), src_w - w))
    y = max(0, min(target_y, src_h - h - bottom_guard))
    out.update({"x": x, "y": y, "w": w, "h": h})
    return out


def probe_video_dimensions(path: Path) -> tuple[int, int] | None:
    probe = subprocess.run([FFMPEG_BIN, "-i", str(path)], capture_output=True, text=True)
    dim_m = re.search(r"(\d{3,4})x(\d{3,4})", probe.stderr)
    if not dim_m:
        return None
    return int(dim_m.group(1)), int(dim_m.group(2))


def ffprobe_bin() -> str:
    candidate = Path(FFMPEG_BIN).with_name("ffprobe")
    return str(candidate) if candidate.exists() else "ffprobe"


def feature_enabled(disable_env_name: str) -> bool:
    value = os.environ.get(disable_env_name, "").strip().lower()
    return value not in {"1", "true", "yes", "on"}


def add_video_polish_filter(parts: list[str], base_label: str, output_label: str) -> str:
    if not feature_enabled("CLIP_DISABLE_VIDEO_POLISH"):
        return base_label
    parts.append(f"[{base_label}]{VIDEO_POLISH_FILTER}[{output_label}]")
    return output_label


def has_audio_stream(path: Path) -> bool:
    result = subprocess.run(
        [
            ffprobe_bin(),
            "-v", "error",
            "-select_streams", "a:0",
            "-show_entries", "stream=codec_type",
            "-of", "csv=p=0",
            str(path),
        ],
        capture_output=True,
        text=True,
    )
    return result.returncode == 0 and "audio" in result.stdout


def add_audio_polish_filter(parts: list[str], raw_clip: Path, output_label: str = "aout") -> str | None:
    if not feature_enabled("CLIP_DISABLE_AUDIO_POLISH") or not has_audio_stream(raw_clip):
        return None
    parts.append(f"[0:a]{AUDIO_POLISH_FILTER}[{output_label}]")
    return output_label


def media_map_args(audio_label: str | None) -> list[str]:
    args = ["-map", "[vout]"]
    if audio_label:
        args.extend(["-map", f"[{audio_label}]"])
    else:
        args.extend(["-map", "0:a?"])
    return args


# ---------------------------------------------------------------------------
# Step 1 — Download latest video
# ---------------------------------------------------------------------------

def download_latest_video(channel_url: str, output_dir: Path) -> Path:
    """
    Download the most recent completed livestream from a YouTube channel.

    Works with /streams URLs (e.g. https://www.youtube.com/@padreydecanocom/streams)
    as well as regular channel URLs.  Skips any ongoing live broadcast.
    """
    print("\n[1/6] Downloading latest completed livestream…")

    # Normalise: ensure we point at the /streams tab so yt-dlp lists past live
    # videos first.  If the user already passed a /streams URL keep it as-is.
    if "/streams" not in channel_url:
        streams_url = channel_url.rstrip("/") + "/streams"
    else:
        streams_url = channel_url

    # Retrieve the ID of the most recent *completed* stream (was_live == True,
    # and not currently live).
    result = run([
        *ytdlp_hq_cmd(),
        "--playlist-end", "3",            # check first 3 in case one is live
        "--match-filter", "was_live & !is_live",
        "--print", "%(id)s\t%(title)s",
        streams_url,
    ])

    lines = [l for l in result.stdout.strip().split("\n") if "\t" in l]
    if not lines:
        print("[ERROR] No completed livestreams found in the channel.", file=sys.stderr)
        print("  Tip: make sure the channel has past streams and is not currently live.", file=sys.stderr)
        sys.exit(1)

    video_id, title = lines[0].split("\t", 1)
    print(f"  → Latest stream: [{video_id}] {title}")

    video_path = output_dir / f"{video_id}.mp4"
    if video_path.exists():
        print(f"  → Already downloaded, skipping.")
        return video_path

    run([
        *ytdlp_hq_cmd(),
        "-f", YOUTUBE_HQ_FORMAT,
        "--merge-output-format", "mp4",
        "--concurrent-fragments", "8",
        "--retries", "infinite",
        "--fragment-retries", "infinite",
        "--retry-sleep", "fragment:exp=1:30",
        "--write-info-json",
        "-o", str(video_path),
        f"https://www.youtube.com/watch?v={video_id}",
    ])
    return video_path


# ---------------------------------------------------------------------------
# Step 2 — Extract audio
# ---------------------------------------------------------------------------

def extract_audio(video_path: Path, output_dir: Path) -> Path:
    print("\n[2/6] Extracting audio…")
    audio_path = output_dir / f"{video_path.stem}.wav"
    if audio_path.exists():
        print(f"  → Already extracted, skipping.")
        return audio_path

    run([
        FFMPEG_BIN, "-y",
        "-i", str(video_path),
        "-vn",
        "-acodec", "pcm_s16le",
        "-ar", "16000",
        "-ac", "1",
        str(audio_path),
    ])
    return audio_path


# ---------------------------------------------------------------------------
# Step 3 — Transcribe with Whisper
# ---------------------------------------------------------------------------

def transcript_has_word_timestamps(transcript: dict) -> bool:
    """True when the cached transcript has usable per-word timing data."""
    for seg in transcript.get("segments", []):
        for word in seg.get("words") or []:
            if "start" in word and "end" in word and str(word.get("word", "")).strip():
                return True
    return False


def transcribe_audio(audio_path: Path, output_dir: Path, model_size: str = "medium") -> dict:
    print(f"\n[3/6] Transcribing with Whisper ({model_size})…")
    transcript_path = output_dir / f"{audio_path.stem}_transcript.json"

    if transcript_path.exists():
        with open(transcript_path, encoding="utf-8") as f:
            cached = json.load(f)
        if transcript_has_word_timestamps(cached):
            print(f"  → Transcript found, loading from cache.")
            return cached
        backup_path = transcript_path.with_suffix(".no_word_timestamps.bak.json")
        print("  → Cached transcript has no word timestamps; regenerating for accurate subtitles.")
        if not backup_path.exists():
            shutil.copy(transcript_path, backup_path)

    try:
        import whisper  # type: ignore
        model = whisper.load_model(model_size)
        result = model.transcribe(
            str(audio_path),
            language="es",
            verbose=False,
            word_timestamps=True,
            initial_prompt=WHISPER_INITIAL_PROMPT,
        )
    except ImportError:
        print("  openai-whisper not found as library, trying CLI…")
        run([
            "whisper", str(audio_path),
            "--language", "es",
            "--model", model_size,
            "--word_timestamps", "True",
            "--initial_prompt", WHISPER_INITIAL_PROMPT,
            "--output_format", "json",
            "--output_dir", str(output_dir),
        ])
        cli_out = output_dir / f"{audio_path.stem}.json"
        with open(cli_out, encoding="utf-8") as f:
            result = json.load(f)

    write_text_if_changed(transcript_path, json.dumps(result, ensure_ascii=False, indent=2))

    total = len(result.get("segments", []))
    print(f"  → {total} segments transcribed, saved to {transcript_path.name}")
    return result


# ---------------------------------------------------------------------------
# Step 4 — Select best moments
# ---------------------------------------------------------------------------

def select_moments(transcript: dict, num_clips: int = 10, output_dir: Path = None) -> list[dict]:
    print(f"\n[4/6] Selecting {num_clips} best moments…")

    moments_path = output_dir / "moments.json" if output_dir else None
    if moments_path and moments_path.exists():
        print(f"  → Moments found, loading from cache.")
        with open(moments_path, encoding="utf-8") as f:
            return json.load(f)

    # Codex normally creates moments.json after reading the saved transcript.
    # Claude is still supported as an optional shortcut, but it is not required
    # for the user's workflow.
    if not os.environ.get("ANTHROPIC_API_KEY"):
        transcript_name = "VIDEO_ID_transcript.json"
        if output_dir:
            transcripts = sorted(output_dir.glob("*_transcript.json"), key=lambda p: p.stat().st_mtime, reverse=True)
            if transcripts:
                transcript_name = transcripts[0].name
        print("  → Todavía no existe moments.json.")
        print(f"  → La transcripción quedó guardada en {transcript_name}.")
        print("  → Elegí los momentos, guardá moments.json y relanzá el mismo comando para continuar sin repetir descarga ni Whisper.")
        sys.exit(2)

    # Build a condensed transcript string (max ~6000 tokens for the prompt)
    segments = transcript.get("segments", [])
    lines = [f"[{s['start']:.1f}s–{s['end']:.1f}s] {s['text'].strip()}" for s in segments]
    transcript_text = "\n".join(lines)

    # If transcript is very long, sample evenly to avoid token overflow
    if len(transcript_text) > 40_000:
        step = len(lines) // 600
        sampled = lines[::step]
        transcript_text = "\n".join(sampled)
        print(f"  → Transcript too long, sampled {len(sampled)} lines for analysis.")

    client = anthropic.Anthropic()

    prompt = f"""Sos un experto en contenido viral para redes sociales, especializado en programas de fútbol uruguayo.

Analizá esta transcripción de un livestream de fans de Peñarol (club de fútbol uruguayo) y seleccioná los {num_clips} momentos MÁS POTENTES para recortar como clips cortos.

Buscá específicamente:
- Debates acalorados entre panelistas con una postura clara
- Reacciones fuertes (goles, noticias, jugadas polémicas, hinchas enojados)
- Momentos graciosos, chicanas, memes o situaciones inesperadas
- Análisis tácticos o técnicos con una conclusión potente
- Frases memorables que puedan funcionar solas en Instagram/TikTok/X
- Momentos de tensión, emoción pura o euforia
- Predicciones u opiniones controversiales sobre jugadores/DT

Score editorial para elegir:
- Hook inmediato: la primera frase debe enganchar sin necesitar 2 minutos de contexto.
- Desarrollo: tiene que pasar algo durante el clip, no solo una idea repetida.
- Remate: debe cerrar en frase completa, risa, silencio o conclusión.
- Publicabilidad: evitar tramos confusos, internos o demasiado largos sin payoff.
- Variedad: no elegir 10 clips del mismo tema si hay otros momentos fuertes.

TRANSCRIPCIÓN:
{transcript_text}

Respondé ÚNICAMENTE con JSON válido con esta estructura exacta (sin texto adicional):
{{
  "clips": [
    {{
      "rank": 1,
      "start": 123.4,
      "end": 200.0,
      "title": "Título corto y viral (máx 60 chars)",
      "reason": "Por qué este momento es potente para redes",
      "hook": "Primera frase/gancho para el clip"
    }}
  ]
}}

Reglas OBLIGATORIAS:
- Cada clip debe durar idealmente entre 40 y 60 segundos (end - start)
- Comenzá el clip 2-3 segundos ANTES del momento clave para dar contexto
- Terminá en un momento de cierre natural (risa, silencio, afirmación)
- Los clips NO pueden superponerse entre sí
- Priorizá inicio con gancho fuerte (la primera frase debe enganchar)
- Evitá comienzos con muletillas, saludos, contexto flojo o frases ya empezadas
- Rankeá del 1 (más viral) al {num_clips} (décimo más viral)
- Usá timestamps exactos de la transcripción
"""

    message = client.messages.create(
        model="claude-opus-4-6",
        max_tokens=4096,
        messages=[{"role": "user", "content": prompt}],
    )

    raw = message.content[0].text.strip()

    # Extract JSON robustly
    json_match = re.search(r"\{[\s\S]*\}", raw)
    if not json_match:
        print("[ERROR] Claude returned unexpected format:", raw[:200], file=sys.stderr)
        sys.exit(1)

    data = json.loads(json_match.group())
    moments = data["clips"]

    if moments_path:
        with open(moments_path, "w", encoding="utf-8") as f:
            json.dump(moments, f, ensure_ascii=False, indent=2)
        print(f"  → {len(moments)} moments saved to {moments_path.name}")

    return moments


# ---------------------------------------------------------------------------
# Step 5 — Cut raw clips
# ---------------------------------------------------------------------------

def cut_clip(video_path: Path, start: float, end: float, output_path: Path) -> None:
    """Cut a segment from the source video (re-encode to ensure clean keyframes)."""
    dur = end - start
    run([
        FFMPEG_BIN, "-y",
        "-ss", str(start),
        "-i", str(video_path),
        "-t", str(dur),
        "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF,
        "-c:a", "aac", "-b:a", AUDIO_BITRATE,
        "-movflags", "+faststart",
        str(output_path),
    ])


def clip_meta_path(raw_path: Path) -> Path:
    return raw_path.with_suffix(".clip.json")


def clip_cache_matches(raw_path: Path, source_path: Path, start: float, end: float) -> bool:
    if not raw_path.exists():
        return False
    meta_path = clip_meta_path(raw_path)
    if not meta_path.exists():
        return False
    try:
        meta = json.loads(meta_path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return False
    return (
        meta.get("source") == source_path.name
        and abs(float(meta.get("start", -1)) - start) < 0.02
        and abs(float(meta.get("end", -1)) - end) < 0.02
    )


def write_clip_cache_meta(raw_path: Path, source_path: Path, start: float, end: float) -> None:
    meta = {
        "source": source_path.name,
        "start": round(start, 3),
        "end": round(end, 3),
        "duration": round(end - start, 3),
    }
    write_text_if_changed(clip_meta_path(raw_path), json.dumps(meta, ensure_ascii=False, indent=2))


# ---------------------------------------------------------------------------
# Step 6 — Generate SRT and encode final clips
# ---------------------------------------------------------------------------

def generate_srt(segments: list[dict], clip_start: float, clip_end: float, srt_path: Path) -> None:
    """Write an SRT file with timestamps relative to the clip's start."""
    entries = []
    counter = 1
    for seg in segments:
        s_start, s_end = seg["start"], seg["end"]
        if s_end <= clip_start or s_start >= clip_end:
            continue
        adj_start = max(0.0, s_start - clip_start)
        adj_end = min(clip_end - clip_start, s_end - clip_start)
        text = normalize_subtitle_text(seg["text"])
        if not text:
            continue
        entries.append(f"{counter}\n{srt_time(adj_start)} --> {srt_time(adj_end)}\n{text}\n")
        counter += 1

    with open(srt_path, "w", encoding="utf-8") as f:
        f.write("\n".join(entries))


def _ass_time(seconds: float) -> str:
    """Convert float seconds to ASS timestamp format H:MM:SS.cs"""
    h = int(seconds // 3600)
    m = int((seconds % 3600) // 60)
    s = seconds % 60
    return f"{h}:{m:02d}:{s:05.2f}"


def _ass_escape_text(text: str) -> str:
    """Escape user/transcript text so it cannot be parsed as ASS override tags."""
    return text.replace("\\", "/").replace("{", "(").replace("}", ")")


def _wrap_subtitle_chunk(words: list[str], max_line_chars: int = 22) -> str:
    """Return one or two balanced ASS lines for a short word chunk."""
    if not words:
        return ""
    if len(" ".join(words)) <= max_line_chars or len(words) == 1:
        return " ".join(words)

    best_i = 1
    best_score = float("inf")
    for i in range(1, len(words)):
        left = " ".join(words[:i])
        right = " ".join(words[i:])
        overflow = max(0, len(left) - max_line_chars) + max(0, len(right) - max_line_chars)
        balance = abs(len(left) - len(right))
        score = overflow * 100 + balance
        if score < best_score:
            best_i = i
            best_score = score

    return " ".join(words[:best_i]) + r"\N" + " ".join(words[best_i:])


def _subtitle_chunks(text: str, max_words: int = 5, max_chars: int = 34) -> list[list[str]]:
    """Split a Whisper segment into short social-clip subtitle beats."""
    words = text.split()
    chunks: list[list[str]] = []
    current: list[str] = []

    for word in words:
        candidate = [*current, word]
        if current and (len(candidate) > max_words or len(" ".join(candidate)) > max_chars):
            chunks.append(current)
            current = [word]
        else:
            current = candidate

    if current:
        chunks.append(current)
    return chunks


def _subtitle_word_chunks(words: list[dict], max_words: int = 5, max_chars: int = 34) -> list[list[dict]]:
    """Split Whisper word-timestamp items into short social-clip subtitle beats."""
    chunks: list[list[dict]] = []
    current: list[dict] = []

    for word in words:
        candidate = [*current, word]
        candidate_text = " ".join(str(item["word"]) for item in candidate)
        if current and (len(candidate) > max_words or len(candidate_text) > max_chars):
            chunks.append(current)
            current = [word]
        else:
            current = candidate

    if current:
        chunks.append(current)
    return chunks


def generate_ass(
    segments: list[dict],
    clip_start: float,
    clip_end: float,
    ass_path: Path,
    play_res_x: int = 1080,
    play_res_y: int = 1920,
    font_size: int = 72,
    margin_v: int = 120,
) -> bool:
    """Write a styled ASS subtitle file with timestamps relative to clip start.

    Using ASS instead of SRT+force_style avoids ffmpeg 8.x filter-complex
    escaping issues with colons and special characters in the style string.
    """
    header = (
        "[Script Info]\n"
        "ScriptType: v4.00+\n"
        "Collisions: Normal\n"
        f"PlayResX: {play_res_x}\n"
        f"PlayResY: {play_res_y}\n"
        "Timer: 100.0000\n\n"
        "[V4+ Styles]\n"
        "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, "
        "OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, "
        "ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, "
        "Alignment, MarginL, MarginR, MarginV, Encoding\n"
        f"Style: Default,Arial Black,{font_size},"
        "&H00FFFFFF,&H000000FF,&H00000000,&HA0000000,"
        f"-1,0,0,0,100,100,0,0,1,8,3,2,70,70,{margin_v},1\n\n"
        "[Events]\n"
        "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n"
    )
    lines = [header]
    for seg in segments:
        s_start, s_end = seg["start"], seg["end"]
        if s_end <= clip_start or s_start >= clip_end:
            continue
        adj_start = max(0.0, s_start - clip_start)
        adj_end = min(clip_end - clip_start, s_end - clip_start)
        segment_text = str(seg.get("text", ""))
        word_items = []
        for item in seg.get("words") or []:
            word = subtitle_display_text(str(item.get("word", "")).strip(), context=segment_text)
            if not word:
                continue
            w_start = float(item.get("start", s_start))
            w_end = float(item.get("end", s_end))
            if w_end <= clip_start or w_start >= clip_end:
                continue
            word_items.append({
                "word": word,
                "start": max(0.0, w_start - clip_start),
                "end": min(clip_end - clip_start, w_end - clip_start),
            })
        if word_items:
            normalize_subtitle_word_sequence(word_items)
            for chunk in _subtitle_word_chunks(word_items):
                chunk_start = max(0.0, min(item["start"] for item in chunk))
                chunk_end = max(item["end"] for item in chunk)
                if chunk_end <= chunk_start:
                    continue
                escaped_chunk = [_ass_escape_text(item["word"]) for item in chunk]
                chunk_text = _wrap_subtitle_chunk(escaped_chunk)
                lines.append(
                    f"Dialogue: 0,{_ass_time(chunk_start)},{_ass_time(chunk_end)},"
                    f"Default,,0,0,0,,{{\\fad(60,60)\\blur0.4}}{chunk_text}"
                )
            continue

        text = subtitle_display_text(segment_text)
        if not text:
            continue
        chunks = _subtitle_chunks(text)
        total_words = sum(len(chunk) for chunk in chunks)
        if not chunks or total_words == 0:
            continue

        elapsed_words = 0
        duration = max(0.01, adj_end - adj_start)
        for chunk in chunks:
            chunk_start = adj_start + duration * elapsed_words / total_words
            elapsed_words += len(chunk)
            chunk_end = adj_start + duration * elapsed_words / total_words
            escaped_chunk = [_ass_escape_text(word) for word in chunk]
            chunk_text = _wrap_subtitle_chunk(escaped_chunk)
            lines.append(
                f"Dialogue: 0,{_ass_time(chunk_start)},{_ass_time(chunk_end)},"
                f"Default,,0,0,0,,{{\\fad(60,60)\\blur0.4}}{chunk_text}"
            )

    return write_text_if_changed(ass_path, "\n".join(lines))


def _looks_like_sentence_end(text: str) -> bool:
    text = normalize_subtitle_text(text)
    if not text:
        return False
    return bool(re.search(r"[.!?…][\"')\]]*$", text))


def snap_end_to_sentence(start: float, end: float, segments: list[dict], tolerance: float = 6.0) -> float:
    """
    Snap clip end to a natural Whisper boundary near the selected end.

    Prefer punctuation or a real pause, and allow a tiny tail so the clip does not
    feel chopped off. Keep the total duration inside the social clip max.
    """
    if not segments:
        return end

    upper = min(end + tolerance, start + ABSOLUTE_MAX_CLIP_DURATION)
    min_end = start + 24.0
    candidates: list[tuple[float, float, float | None]] = []
    boundaries: list[float] = []

    for idx, seg in enumerate(segments):
        s_start = float(seg.get("start", 0.0))
        s_end = float(seg.get("end", 0.0))
        if s_start < start - 0.25 or s_end < min_end or s_end > upper:
            continue

        next_start = None
        if idx + 1 < len(segments):
            next_start = float(segments[idx + 1].get("start", s_end))
        gap_after = max(0.0, next_start - s_end) if next_start is not None else 0.0
        punctuation = _looks_like_sentence_end(str(seg.get("text", "")))
        natural_pause = gap_after >= 0.42
        boundaries.append(s_end)

        if not punctuation and not natural_pause:
            continue

        # Prefer a natural boundary close to the selected end. If two are close,
        # favor extending over cutting early, and punctuation over mere silence.
        score = abs(s_end - end)
        if s_end < end:
            score += 0.45
        if not punctuation:
            score += 0.25
        candidates.append((score, s_end, next_start))

    if candidates:
        _, snapped, next_start = min(candidates, key=lambda item: item[0])
        if next_start is None:
            pad = END_PAD_SECONDS
        else:
            pad = min(END_PAD_SECONDS, max(0.0, next_start - snapped))
        return min(snapped + pad, start + ABSOLUTE_MAX_CLIP_DURATION)

    if boundaries:
        return max(boundaries)
    return min(end, start + ABSOLUTE_MAX_CLIP_DURATION)


def snap_start_to_segment(start: float, segments: list[dict], tolerance: float = 3.0) -> float:
    """
    If the selected moment starts inside a Whisper segment, move the clip start
    back to that segment boundary. Without word-level timestamps, burning the
    full segment text over only the tail of the audio makes subtitles look early.
    """
    for seg in segments:
        s_start = float(seg["start"])
        s_end = float(seg["end"])
        if s_start < start < s_end and start - s_start <= tolerance:
            return s_start
    return start


def detect_speaker_zoom(raw_clip: Path, n_samples: int = 6) -> dict | None:
    """
    Detect the PRIMARY speaker face and return crop params for smart 9:16 zoom.

    Strategy:
      1. Sample n_samples frames evenly across the clip.
      2. Detect faces with Haar cascade; discard any face whose centre is below
         55 % of the frame height — those are false positives (jersey logos,
         microphone stands, sponsor boards, etc.).
      3. Among valid faces, pick the LARGEST one (highest pixel area).  The
         largest face is the person sitting closest to camera, which is virtually
         always the active speaker in a podcast/talk-show setting.
      4. Accumulate the position of the chosen face across frames and use the
         median centre so that small per-frame jitter doesn't shift the crop.
      5. If no valid face is found in any frame, fall back to a centre crop of
         the upper portion of the frame (always better than a blurred pillarbox).

    Returns dict {x, y, w, h, faces, src_w, src_h} in source video coords, or None
    only when cv2 is not importable.
    """
    try:
        import cv2
    except ImportError:
        return None

    # --- Get clip duration and dimensions ---
    probe = subprocess.run([FFMPEG_BIN, "-i", str(raw_clip)], capture_output=True, text=True)
    dim_m = re.search(r"(\d{3,4})x(\d{3,4})", probe.stderr)
    dur_m = re.search(r"Duration:\s*(\d+):(\d+):([\d.]+)", probe.stderr)
    if not dim_m or not dur_m:
        return None
    src_w, src_h = int(dim_m.group(1)), int(dim_m.group(2))
    duration = int(dur_m.group(1)) * 3600 + int(dur_m.group(2)) * 60 + float(dur_m.group(3))

    cascade_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
    face_cascade = cv2.CascadeClassifier(cascade_path)
    eye_cascades = [
        cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye_tree_eyeglasses.xml"),
        cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml"),
    ]

    # Sample frames at evenly spaced timestamps (skip first/last 5 % to avoid fades)
    margin = max(2.0, duration * 0.05)
    sample_times = [
        margin + (duration - 2 * margin) * i / (n_samples - 1)
        for i in range(n_samples)
    ]

    # Valid-face y-threshold: faces whose centre is below this are false positives
    # (logos, jersey numbers, desk objects) and must be ignored.
    valid_y_max = src_h * 0.55

    # Per-frame: record the (cx, cy, area) of the largest valid face found
    best_cx_list: list[int] = []
    best_cy_list: list[int] = []
    best_area: int = 0
    panel_hits = 0

    for t in sample_times:
        with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f:
            frame_path = f.name
        try:
            subprocess.run(
                [FFMPEG_BIN, "-ss", str(t), "-i", str(raw_clip),
                 "-frames:v", "1", "-q:v", "2", "-y", frame_path],
                capture_output=True, check=True,
            )
            img = cv2.imread(frame_path)
        except Exception:
            continue
        finally:
            with contextlib.suppress(FileNotFoundError):
                os.unlink(frame_path)

        if img is None:
            continue

        if _is_split_panel_frame(img, src_w):
            panel_hits += 1

        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=4, minSize=(40, 40))
        if not len(faces):
            continue

        # Keep only real-looking faces whose centre is in the upper 55 % of the
        # frame. Eye validation is important: studio signs, score tables and
        # sponsor graphics routinely trigger Haar "faces" and caused ultra-tight
        # crops of posters instead of journalists.
        valid = []
        weak = []
        for (fx, fy, fw, fh) in faces:
            if (fy + fh / 2) >= valid_y_max:
                continue
            if fw * fh < 8000:
                continue
            upper = gray[fy:fy + int(fh * 0.62), fx:fx + fw]
            eye_count = 0
            if upper.size:
                for eye_cascade in eye_cascades:
                    if eye_cascade.empty():
                        continue
                    eyes = eye_cascade.detectMultiScale(
                        upper,
                        scaleFactor=1.05,
                        minNeighbors=3,
                        minSize=(max(14, fw // 10), max(10, fh // 14)),
                    )
                    eye_count = max(eye_count, len(eyes))
            if eye_count >= 2:
                valid.append((fx, fy, fw, fh))
            elif eye_count >= 1:
                weak.append((fx, fy, fw, fh))
        if not valid:
            valid = weak
        if not valid:
            continue

        # Pick the largest valid face in this frame (= closest / most prominent)
        fx, fy, fw, fh = max(valid, key=lambda f: f[2] * f[3])
        best_cx_list.append(fx + fw // 2)
        best_cy_list.append(fy + fh // 2)
        best_area = max(best_area, fw * fh)

    if not best_cx_list:
        if panel_hits >= max(2, n_samples // 2):
            crop = _panel_crop_for_zone(src_w, src_h, 1)
            return {**crop, "faces": 0, "src_w": src_w, "src_h": src_h}

        # No valid face found in any frame — use a centre crop of the upper body.
        # A tight centre crop is always better than a blurred pillarbox.
        crop_h = _clean_closeup_height(src_h)
        crop_w = int(crop_h * 9 / 16)
        if crop_w > src_w:
            crop_w = src_w
            crop_h = int(crop_w * 16 / 9)
        crop_x = (src_w - crop_w) // 2
        crop_y = _vertical_closeup_y(src_h, crop_h)
        crop = avoid_source_logo_crop(
            {"x": crop_x, "y": crop_y, "w": crop_w, "h": crop_h},
            src_w,
            src_h,
        )
        return {**crop, "faces": 0, "src_w": src_w, "src_h": src_h}

    # Median centre across frames (robust against jitter/occasional missed detections)
    best_cx_list.sort()
    best_cy_list.sort()
    face_center_x = best_cx_list[len(best_cx_list) // 2]
    face_center_y = best_cy_list[len(best_cy_list) // 2]
    face_side = int(best_area ** 0.5)  # approximate face size (square root of area)

    if panel_hits >= max(2, n_samples // 2):
        crop = _panel_crop_for_zone(src_w, src_h, _panel_zone_for_x(src_w, face_center_x))
        return {**crop, "faces": len(best_cx_list), "src_w": src_w, "src_h": src_h}

    # 9:16 crop: face + generous head/upper-body padding
    crop_h = min(int(face_side * 4.5), _clean_closeup_height(src_h))
    crop_w = int(crop_h * 9 / 16)
    if crop_w > src_w:
        crop_w = src_w
        crop_h = int(crop_w * 16 / 9)

    # Anchor crop so face is in the upper-third of the vertical frame
    crop_x = max(0, min(face_center_x - crop_w // 2, src_w - crop_w))
    crop_y = max(0, min(face_center_y - crop_h // 4, src_h - crop_h))
    crop_y = min(crop_y, _vertical_closeup_y(src_h, crop_h))

    crop = avoid_source_logo_crop(
        {"x": crop_x, "y": crop_y, "w": crop_w, "h": crop_h},
        src_w,
        src_h,
    )
    return {**crop, "faces": len(best_cx_list), "src_w": src_w, "src_h": src_h}


def encode_vertical(raw_clip: Path, ass_path: Path, output_path: Path) -> None:
    """
    Produce 1080×1920 (9:16) clip with blurred background.
    Layout: blurred full-bleed background + centred original video + burned subtitles.
    Uses a pre-generated ASS file (style embedded) to avoid ffmpeg filter escaping issues.
    """
    with tempfile.TemporaryDirectory() as tmp:
        tmp_ass = Path(tmp) / "sub.ass"
        shutil.copy(ass_path, tmp_ass)
        # Escape only backslashes and colons for ffmpeg filter path
        esc = str(tmp_ass).replace("\\", "/").replace(":", r"\:")

        logo_path = pyd_logo_path()
        logo_input = ["-i", str(logo_path)] if logo_path else []
        parts = [
            "[0:v]scale=1080:1920:force_original_aspect_ratio=increase:flags=lanczos,"
            "crop=1080:1920,boxblur=25:5[bg]",
            "[0:v]scale=1080:-2:flags=lanczos[fg]",
            "[bg][fg]overlay=(W-w)/2:(H-h)/2[base]",
        ]
        video_label = "base"
        video_label = add_video_polish_filter(parts, video_label, "polished")
        if logo_path:
            video_label = add_pyd_logo_filter(parts, video_label, 1, "branded", vertical=True)
        parts.append(f"[{video_label}]subtitles={esc}[vout]")
        audio_label = add_audio_polish_filter(parts, raw_clip)
        filter_complex = ";".join(parts)
        map_args = media_map_args(audio_label)

        run([
            FFMPEG_BIN, "-y",
            "-i", str(raw_clip),
            *logo_input,
            "-filter_complex", filter_complex,
            *map_args,
            "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF,
            "-c:a", "aac", "-b:a", AUDIO_BITRATE,
            "-movflags", "+faststart",
            str(output_path),
        ])


def encode_vertical_interview_layout(raw_clip: Path, ass_path: Path, output_path: Path) -> None:
    """
    Produce a vertical interview composition that keeps the guest large while
    preserving the three small journalist panels from the source layout.
    """
    dims = probe_video_dimensions(raw_clip)
    if not dims:
        print("    → No pude medir el layout de entrevista; uso encuadre estándar")
        encode_vertical(raw_clip, ass_path, output_path)
        return

    src_w, src_h = dims
    remote_guest = is_remote_guest_interview_clip(raw_clip)
    if remote_guest:
        guest_x = max(0, int(src_w * 0.15))
        guest_y = max(0, int(src_h * 0.088))
        guest_w = min(src_w - guest_x, int(src_w * 0.70))
        guest_h = min(src_h - guest_y, int(src_h * 0.60))
        strip_x = max(0, int(src_w * 0.2375))
        strip_y = max(0, int(src_h * 0.676))
        strip_w = min(src_w - strip_x, int(src_w * 0.55))
        strip_h = min(src_h - strip_y, int(src_h * 0.296))
        print(
            "    → Layout entrevista remota: invitado limpio + paneles completos "
            f"(guest {guest_w}×{guest_h}@{guest_x},{guest_y}; "
            f"strip {strip_w}×{strip_h}@{strip_x},{strip_y})"
        )

        with tempfile.TemporaryDirectory() as tmp:
            tmp_ass = Path(tmp) / "sub.ass"
            shutil.copy(ass_path, tmp_ass)
            esc = str(tmp_ass).replace("\\", "/").replace(":", r"\:")

            logo_path = pyd_logo_path()
            logo_input = ["-i", str(logo_path)] if logo_path else []
            parts = [
                "[0:v]scale=1080:1920:force_original_aspect_ratio=increase:flags=lanczos,"
                "crop=1080:1920,boxblur=30:5,eq=brightness=-0.08:saturation=0.90[bg]",
                f"[0:v]crop={guest_w}:{guest_h}:{guest_x}:{guest_y},"
                "scale=1080:960:force_original_aspect_ratio=increase:flags=lanczos,"
                "crop=1080:960[guest]",
                f"[0:v]crop={strip_w}:{strip_h}:{strip_x}:{strip_y},"
                "scale=1018:-2:flags=lanczos,"
                "pad=iw+12:ih+12:6:6:color=0xE5C01D[strip]",
                "[bg][guest]overlay=0:54[stage_guest]",
                "[stage_guest][strip]overlay=(W-w)/2:1168[base]",
            ]
            video_label = "base"
            video_label = add_video_polish_filter(parts, video_label, "polished")
            if logo_path:
                video_label = add_pyd_logo_filter(parts, video_label, 1, "branded", vertical=True)
            parts.append(f"[{video_label}]subtitles={esc}[vout]")
            audio_label = add_audio_polish_filter(parts, raw_clip)
            filter_complex = ";".join(parts)
            map_args = media_map_args(audio_label)

            run([
                FFMPEG_BIN, "-y",
                "-i", str(raw_clip),
                *logo_input,
                "-filter_complex", filter_complex,
                *map_args,
                "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF,
                "-c:a", "aac", "-b:a", AUDIO_BITRATE,
                "-movflags", "+faststart",
                str(output_path),
            ])
        return

    guest_x = max(0, int(src_w * 0.05))
    guest_y = max(0, int(src_h * 0.05))
    guest_w = min(src_w - guest_x, int(src_w * 0.78))
    guest_h = min(src_h - guest_y, int(src_h * 0.51))
    strip_x = max(0, int(src_w * 0.10))
    strip_y = max(0, int(src_h * 0.56))
    strip_w = min(src_w - strip_x, int(src_w * 0.76))
    strip_h = min(src_h - strip_y, int(src_h * 0.36))

    print(
        "    → Layout entrevista: invitado grande + tira completa de periodistas "
        f"(guest {guest_w}×{guest_h}@{guest_x},{guest_y}; strip {strip_w}×{strip_h}@{strip_x},{strip_y})"
    )

    with tempfile.TemporaryDirectory() as tmp:
        tmp_ass = Path(tmp) / "sub.ass"
        shutil.copy(ass_path, tmp_ass)
        esc = str(tmp_ass).replace("\\", "/").replace(":", r"\:")

        logo_path = pyd_logo_path()
        logo_input = ["-i", str(logo_path)] if logo_path else []
        parts = [
            "[0:v]scale=1080:1920:force_original_aspect_ratio=increase:flags=lanczos,"
            "crop=1080:1920,boxblur=30:5,eq=brightness=-0.08:saturation=0.90[bg]",
            f"[0:v]crop={guest_w}:{guest_h}:{guest_x}:{guest_y},"
            "scale=1080:930:force_original_aspect_ratio=increase:flags=lanczos,"
            "crop=1080:930[guest]",
            f"[0:v]crop={strip_w}:{strip_h}:{strip_x}:{strip_y},"
            "scale=1018:-2:flags=lanczos,"
            "pad=iw+12:ih+12:6:6:color=0xE5C01D[strip]",
            "[bg][guest]overlay=0:126[stage_guest]",
            "[stage_guest][strip]overlay=(W-w)/2:1088[base]",
        ]
        video_label = "base"
        video_label = add_video_polish_filter(parts, video_label, "polished")
        if logo_path:
            video_label = add_pyd_logo_filter(parts, video_label, 1, "branded", vertical=True)
        parts.append(f"[{video_label}]subtitles={esc}[vout]")
        audio_label = add_audio_polish_filter(parts, raw_clip)
        filter_complex = ";".join(parts)
        map_args = media_map_args(audio_label)

        run([
            FFMPEG_BIN, "-y",
            "-i", str(raw_clip),
            *logo_input,
            "-filter_complex", filter_complex,
            *map_args,
            "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF,
            "-c:a", "aac", "-b:a", AUDIO_BITRATE,
            "-movflags", "+faststart",
            str(output_path),
        ])


def encode_vertical_zoom(raw_clip: Path, ass_path: Path, output_path: Path) -> None:
    """
    Produce 1080×1920 (9:16) clip with smart zoom to speaker face area.
    Detects faces with OpenCV Haar cascade and crops/zooms to them.
    Falls back to standard blurred-background encoding if no faces found.
    """
    crop = detect_speaker_zoom(raw_clip)

    if crop is None:
        # detect_speaker_zoom now always returns a crop; this branch is kept as a
        # safety net in case cv2 import fails entirely.
        print("    → cv2 no disponible, usando encuadre estándar (blur)")
        encode_vertical(raw_clip, ass_path, output_path)
        return

    if crop["faces"] == 0:
        print(f"    → Sin caras detectadas — center crop {crop['w']}×{crop['h']} "
              f"→ 1080×1920")
    else:
        print(f"    → {crop['faces']} cara(s) detectada(s) — zoom {crop['src_w']}×{crop['src_h']} "
          f"→ crop {crop['w']}×{crop['h']} → 1080×1920")

    with tempfile.TemporaryDirectory() as tmp:
        tmp_ass = Path(tmp) / "sub.ass"
        shutil.copy(ass_path, tmp_ass)
        esc = str(tmp_ass).replace("\\", "/").replace(":", r"\:")

        logo_path = pyd_logo_path()
        logo_input = ["-i", str(logo_path)] if logo_path else []
        parts = [
            f"[0:v]crop={crop['w']}:{crop['h']}:{crop['x']}:{crop['y']},"
            "scale=1080:1920:force_original_aspect_ratio=increase:flags=lanczos,"
            "crop=1080:1920[base]"
        ]
        video_label = "base"
        video_label = add_video_polish_filter(parts, video_label, "polished")
        if logo_path:
            video_label = add_pyd_logo_filter(parts, video_label, 1, "branded", vertical=True)
        parts.append(f"[{video_label}]subtitles={esc}[vout]")
        audio_label = add_audio_polish_filter(parts, raw_clip)
        filter_complex = ";".join(parts)
        map_args = media_map_args(audio_label)
        run([
            FFMPEG_BIN, "-y",
            "-i", str(raw_clip),
            *logo_input,
            "-filter_complex", filter_complex,
            *map_args,
            "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF,
            "-c:a", "aac", "-b:a", AUDIO_BITRATE,
            "-movflags", "+faststart",
            str(output_path),
        ])


def _vertical_top_guard_y(src_h: int, crop_h: int) -> int:
    """Small y-offset to remove the source's top broadcast border from crops."""
    return min(int(src_h * VERTICAL_TOP_GUARD_RATIO), max(0, src_h - crop_h))


def _clean_closeup_height(src_h: int) -> int:
    """Crop height that leaves the source's top and bottom layout borders out."""
    guard = int(src_h * VERTICAL_TOP_GUARD_RATIO)
    return max(1, src_h - (guard * 2))


def _vertical_closeup_y(src_h: int, crop_h: int) -> int:
    """Y anchor for single-camera crops; keep layout borders out."""
    return _vertical_top_guard_y(src_h, crop_h)


def _panel_zone_centers(src_w: int, panel_count: int) -> list[int]:
    zone_w = src_w / max(1, panel_count)
    return [int(zone_w * (idx + 0.5)) for idx in range(panel_count)]


def _panel_zone_for_x_count(src_w: int, x: int, panel_count: int) -> int:
    """Map a source x coordinate to a fixed horizontal panel index."""
    zone_w = src_w / max(1, panel_count)
    return max(0, min(panel_count - 1, int(x // max(1.0, zone_w))))


def _panel_crop_for_zone_count(src_w: int, src_h: int, zone_idx: int, panel_count: int) -> dict:
    """Return the clean fixed 9:16 crop for one journalist in an N-panel layout."""
    if panel_count == 4:
        return _four_panel_crop_for_zone(src_w, src_h, zone_idx)

    crop_h = int(src_h * PANEL_CROP_HEIGHT_RATIO)
    crop_w = int(crop_h * 9 / 16)
    if crop_w > src_w:
        crop_w = src_w
        crop_h = int(crop_w * 16 / 9)

    panel_count = max(1, panel_count)
    zone_idx = max(0, min(zone_idx, panel_count - 1))
    zone_w = src_w / panel_count
    cx = int(zone_w * (zone_idx + 0.5))

    # Preserve the older right-panel bias for the 3-panel layout: that journalist
    # often leans toward the centre mic, and anchoring at the panel edge keeps the
    # face inside the vertical crop.
    if panel_count == 3 and zone_idx == 2:
        x = int(2 * zone_w)
    else:
        x = max(0, min(cx - crop_w // 2, src_w - crop_w))

    return avoid_source_logo_crop(
        {"x": x, "y": _vertical_top_guard_y(src_h, crop_h), "w": crop_w, "h": crop_h},
        src_w,
        src_h,
    )


def _four_panel_crop_for_zone(
    src_w: int,
    src_h: int,
    zone_idx: int,
    face_box: tuple[int, int, int, int] | None = None,
) -> dict:
    """Return a tight 9:16 crop that stays inside one panel of the 4-up layout."""
    panel_count = 4
    zone_w = src_w / panel_count
    zone_idx = max(0, min(zone_idx, panel_count - 1))

    # Four-up panels are narrower than the usual three-person layout. A crop
    # based on the old panel height is wider than one panel and shows separators.
    inner_left, inner_right = _four_panel_inner_bounds(src_w, zone_idx)
    inner_w = max(1, inner_right - inner_left)

    crop_w = min(inner_w, max(1, int(zone_w * 0.88)))
    crop_h = int(round(crop_w * 16 / 9))
    if crop_h > src_h:
        crop_h = src_h
        crop_w = min(inner_w, max(1, int(crop_h * 9 / 16)))

    if face_box:
        face_cx, face_y, _face_w, face_h = face_box
        desired_x = int(round(face_cx - crop_w * 0.50))
        desired_y = int(round(face_y - crop_h * 0.18))
    else:
        desired_x = int(round(zone_w * (zone_idx + 0.5) - crop_w / 2))
        desired_y = int(src_h * 0.11)

    max_x = inner_right - crop_w
    x = max(inner_left, min(desired_x, max_x))
    bottom_guard = max(0, int(src_h * SOURCE_LOGO_BOTTOM_GUARD_RATIO))
    min_y = max(_vertical_top_guard_y(src_h, crop_h), int(src_h * 0.10))
    max_y = max(0, src_h - crop_h - bottom_guard)
    y = max(0, min(max(desired_y, min_y), max_y))

    return avoid_source_logo_crop({"x": x, "y": y, "w": crop_w, "h": crop_h}, src_w, src_h)


def _four_panel_inner_bounds(src_w: int, zone_idx: int) -> tuple[int, int]:
    """Return the safe horizontal bounds inside one 4-up panel separator."""
    panel_count = 4
    zone_w = src_w / panel_count
    zone_idx = max(0, min(zone_idx, panel_count - 1))
    separator_margin = max(18, int(zone_w * 0.04))
    inner_left = int(round(zone_idx * zone_w + (separator_margin if zone_idx > 0 else 0)))
    inner_right = int(round((zone_idx + 1) * zone_w - (separator_margin if zone_idx < panel_count - 1 else 0)))
    inner_left = max(0, min(src_w - 1, inner_left))
    inner_right = max(inner_left + 1, min(src_w, inner_right))
    return inner_left, inner_right


def _panel_crop_for_zone(src_w: int, src_h: int, zone_idx: int) -> dict:
    """Return the clean fixed 9:16 crop for one journalist in the 3-panel layout."""
    return _panel_crop_for_zone_count(src_w, src_h, zone_idx, 3)


def sanitize_dynamic_crop(seg: dict, src_w: int, src_h: int) -> dict:
    """Repair saved crop plans that are no longer clean for the current layout."""
    out = dict(seg)
    if out.get("layout") == "panel4":
        zone = _panel_zone_for_x_count(src_w, int(out["x"]) + int(out["w"]) // 2, 4)
        inner_left, inner_right = _four_panel_inner_bounds(src_w, zone)
        x = int(out.get("x", 0))
        w = int(out.get("w", 0))
        if w > 0 and x >= inner_left - 2 and x + w <= inner_right + 2:
            out.update(avoid_source_logo_crop(out, src_w, src_h))
        else:
            clean = _panel_crop_for_zone_count(src_w, src_h, zone, 4)
            out.update(clean)
        return out
    out.update(avoid_source_logo_crop(out, src_w, src_h))
    return out


def _two_panel_crop_for_zone(src_w: int, src_h: int, zone_idx: int) -> dict:
    """Return a clean 9:16 crop for one journalist in a 2-panel layout."""
    crop_h = _clean_closeup_height(src_h)
    crop_w = int(crop_h * 9 / 16)
    if crop_w > src_w:
        crop_w = src_w
        crop_h = int(crop_w * 16 / 9)

    half_w = src_w // 2
    zone_idx = max(0, min(zone_idx, 1))
    cx = half_w // 2 + half_w * zone_idx
    if zone_idx == 1:
        # The right-panel speaker often leans toward the centre seam, but their
        # face can also sit far right; bias slightly right to avoid half-face crops.
        cx += int(half_w * 0.08)
    x = max(0, min(cx - crop_w // 2, src_w - crop_w))
    return avoid_source_logo_crop(
        {"x": x, "y": _vertical_closeup_y(src_h, crop_h), "w": crop_w, "h": crop_h},
        src_w,
        src_h,
    )


def _panel_zone_for_x(src_w: int, x: int) -> int:
    """Map a source x coordinate to left/centre/right panel index."""
    return _panel_zone_for_x_count(src_w, x, 3)


def _two_panel_zone_for_x(src_w: int, x: int) -> int:
    """Map a source x coordinate to left/right panel index."""
    return 0 if x < src_w / 2 else 1


def _is_split_panel_frame(img, src_w: int) -> bool:
    """
    Detect the three-panel broadcast layout by its internal yellow separators.

    Active-speaker tracking is reliable only in this layout.  Close-up camera
    shots reuse similar backgrounds and can fool Haar face detection with hands,
    logos, or wall patterns; the yellow dividers are a much stronger signal that
    fixed left/centre/right crops are safe.
    """
    return _is_fixed_panel_frame(img, src_w, 3)


def _yellow_separator_ratio(img, src_w: int, x: int, half_width: int = 12) -> float:
    import cv2

    stripe = img[:, max(0, x - half_width): min(src_w, x + half_width + 1)]
    if stripe.size == 0:
        return 0.0
    b, g, r = cv2.split(stripe)
    yellow = (
        (r > 130)
        & (g > 110)
        & (b < 90)
        & ((r.astype("int16") - b.astype("int16")) > 60)
        & ((g.astype("int16") - b.astype("int16")) > 40)
    )
    return float(yellow.mean())


def _is_fixed_panel_frame(img, src_w: int, panel_count: int) -> bool:
    """Detect a fixed split-panel frame by its internal yellow separators."""
    if panel_count <= 1:
        return False
    separators = [round(src_w * i / panel_count) for i in range(1, panel_count)]
    ratios = [_yellow_separator_ratio(img, src_w, x, half_width=14) for x in separators]
    threshold = 0.08 if panel_count == 2 else 0.12
    required = len(separators)
    return sum(ratio > threshold for ratio in ratios) >= required


def _is_four_panel_frame(img, src_w: int) -> bool:
    """Detect the four-person interview layout before the central 2-panel check."""
    return _is_fixed_panel_frame(img, src_w, 4)


def _is_legacy_split_panel_frame(img, src_w: int) -> bool:
    import cv2

    stripes_ok = 0
    for x in (src_w // 3, 2 * src_w // 3):
        stripe = img[:, max(0, x - 10): min(src_w, x + 11)]
        if stripe.size == 0:
            continue
        b, g, r = cv2.split(stripe)
        yellow = (
            (r > 130)
            & (g > 110)
            & (b < 85)
            & ((r.astype("int16") - b.astype("int16")) > 65)
            & ((g.astype("int16") - b.astype("int16")) > 45)
        )
        if float(yellow.mean()) > 0.15:
            stripes_ok += 1
    return stripes_ok >= 2


def _is_two_panel_frame(img, src_w: int) -> bool:
    """Detect the two-speaker broadcast layout by its central yellow divider."""
    return _is_fixed_panel_frame(img, src_w, 2)


def _is_bottom_strip_layout_frame(img, src_w: int, src_h: int) -> bool:
    """Detect layouts with a large main area and three small panels at the bottom."""
    try:
        import cv2
    except ImportError:
        return False

    lower = img[int(src_h * 0.55): int(src_h * 0.94), :]
    if lower.size == 0:
        return False
    b, g, r = cv2.split(lower)
    yellow = (
        (r > 130)
        & (g > 105)
        & (b < 100)
        & ((r.astype("int16") - b.astype("int16")) > 45)
        & ((g.astype("int16") - b.astype("int16")) > 30)
    )
    lower_yellow_ratio = float(yellow.mean())

    upper = img[int(src_h * 0.04): int(src_h * 0.48), :]
    if upper.size == 0:
        return False
    ub, ug, ur = cv2.split(upper)
    upper_yellow = (
        (ur > 130)
        & (ug > 105)
        & (ub < 100)
        & ((ur.astype("int16") - ub.astype("int16")) > 45)
        & ((ug.astype("int16") - ub.astype("int16")) > 30)
    )
    upper_yellow_ratio = float(upper_yellow.mean())

    # The lower strip is visually dominated by yellow panel frames. Equal split
    # studio layouts have yellow dividers through the upper area too; those
    # should stay in the active-speaker path instead of this composition.
    return lower_yellow_ratio > 0.075 and upper_yellow_ratio < 0.075


def _is_guest_interview_frame(img, src_w: int, src_h: int) -> bool:
    """Backward-compatible alias for the broader bottom-strip layout detector."""
    return _is_bottom_strip_layout_frame(img, src_w, src_h)


def _is_remote_guest_interview_frame(img, src_w: int, src_h: int) -> bool:
    """Detect the subset with a bright remote guest window above the panel strip."""
    try:
        import cv2
    except ImportError:
        return False

    if not _is_bottom_strip_layout_frame(img, src_w, src_h):
        return False
    top = img[int(src_h * 0.03): int(src_h * 0.55), int(src_w * 0.04): int(src_w * 0.86)]
    if top.size == 0:
        return False
    top_brightness = float((cv2.cvtColor(top, cv2.COLOR_BGR2GRAY) > 125).mean())
    return top_brightness > 0.55


def is_guest_interview_clip(raw_clip: Path) -> bool:
    """Return true when the clip should preserve the full interview panel strip."""
    try:
        import cv2
    except ImportError:
        return False

    cap = cv2.VideoCapture(str(raw_clip))
    if not cap.isOpened():
        return False
    fps = cap.get(cv2.CAP_PROP_FPS) or 60
    frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0
    if fps <= 0 or frame_count <= 0:
        cap.release()
        return False
    duration = frame_count / fps
    sample_times = [duration * p for p in (0.08, 0.25, 0.50, 0.75, 0.92)]
    hits = 0
    total = 0
    for sample_t in sample_times:
        cap.set(cv2.CAP_PROP_POS_MSEC, max(0.0, sample_t) * 1000)
        ok, frame = cap.read()
        if not ok:
            continue
        src_h, src_w = frame.shape[:2]
        total += 1
        if _is_guest_interview_frame(frame, src_w, src_h):
            hits += 1
    cap.release()
    return total >= 3 and hits >= max(3, int(total * 0.6))


def is_remote_guest_interview_clip(raw_clip: Path) -> bool:
    """Return true for remote guest layouts that should stay as one full block."""
    try:
        import cv2
    except ImportError:
        return False

    cap = cv2.VideoCapture(str(raw_clip))
    if not cap.isOpened():
        return False
    fps = cap.get(cv2.CAP_PROP_FPS) or 60
    frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0
    if fps <= 0 or frame_count <= 0:
        cap.release()
        return False
    duration = frame_count / fps
    sample_times = [duration * p for p in (0.08, 0.25, 0.50, 0.75, 0.92)]
    hits = 0
    total = 0
    for sample_t in sample_times:
        cap.set(cv2.CAP_PROP_POS_MSEC, max(0.0, sample_t) * 1000)
        ok, frame = cap.read()
        if not ok:
            continue
        src_h, src_w = frame.shape[:2]
        total += 1
        if _is_remote_guest_interview_frame(frame, src_w, src_h):
            hits += 1
    cap.release()
    return total >= 3 and hits >= max(3, int(total * 0.6))


def _safe_closeup_crop(
    frame_files: list[Path],
    frame_indices: list[int],
    face_cascade,
    src_w: int,
    src_h: int,
    crop_w: int,
    crop_h: int,
) -> dict:
    """
    Crop a non-split-screen camera shot.  Prefer a detected face centre, but
    fall back to centre-crop because a close-up presenter is usually centred
    even when profile/microphone occlusion makes Haar miss the face.
    """
    try:
        import cv2
        import numpy as np
    except ImportError:
        cx_values = []
    else:
        cx_values = []
        for idx in frame_indices:
            if idx < 0 or idx >= len(frame_files):
                continue
            img = cv2.imread(str(frame_files[idx]))
            if img is None:
                continue
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            faces = face_cascade.detectMultiScale(
                gray,
                scaleFactor=1.1,
                minNeighbors=5,
                minSize=(max(80, src_w // 18), max(80, src_h // 14)),
            )
            valid = [
                (fx, fy, fw, fh)
                for (fx, fy, fw, fh) in faces
                if (fy + fh / 2) < src_h * 0.68 and fw * fh > 8000
            ]
            if valid:
                fx, fy, fw, fh = max(valid, key=lambda f: f[2] * f[3])
                cx_values.append(int(fx + fw / 2))

    if cx_values:
        cx_values.sort()
        cx = cx_values[len(cx_values) // 2]
    else:
        cx = src_w // 2

    x = max(0, min(cx - crop_w // 2, src_w - crop_w))
    y = _vertical_closeup_y(src_h, crop_h)
    return {"x": x, "y": y, "w": crop_w, "h": crop_h}


def _get_talknet_model():
    """Load the local TalkNet model once. CPU is slower but stable on this Mac."""
    global _TALKNET_MODEL
    if _TALKNET_MODEL is not None:
        return _TALKNET_MODEL
    if not TALKNET_MODEL_PATH.exists():
        return None
    try:
        import torch  # noqa: F401
        import python_speech_features  # noqa: F401
        from scipy.io import wavfile  # noqa: F401
    except Exception:
        return None

    if str(TALKNET_DIR) not in sys.path:
        sys.path.insert(0, str(TALKNET_DIR))
    previous_device = os.environ.get("TALKNET_DEVICE")
    os.environ["TALKNET_DEVICE"] = "cpu"
    try:
        from talkNet import talkNet

        model = talkNet()
        model.loadParameters(str(TALKNET_MODEL_PATH))
        model.eval()
    except Exception:
        if previous_device is None:
            os.environ.pop("TALKNET_DEVICE", None)
        else:
            os.environ["TALKNET_DEVICE"] = previous_device
        return None
    _TALKNET_MODEL = model
    return _TALKNET_MODEL


def _talknet_crop_rect(
    src_w: int,
    src_h: int,
    face: tuple[int, int, int, int],
) -> tuple[int, int, int, int]:
    """Return a fixed square face crop suitable for TalkNet's visual frontend."""
    cx, fy, fw, fh = face
    cy = fy + fh // 2
    side = max(96, int(max(fw, fh) * 1.65))
    side = min(side, src_w, src_h)
    x = int(cx - side / 2)
    y = int(cy - side * 0.42)
    return x, y, side, side


def _smooth_median(values, window: int):
    import numpy as np

    out = np.zeros_like(values)
    half = window // 2
    for i in range(len(values)):
        out[i] = np.median(values[max(0, i - half): min(len(values), i + half + 1)])
    return out


def _fixed_face_motion_matrix(
    raw_clip: Path,
    face_boxes: dict[int, tuple[int, int, int, int]],
    output_len: int,
    duration: float,
) -> object | None:
    """Return per-face lower-face motion aligned to TalkNet's score timeline."""
    try:
        import cv2
        import numpy as np
    except Exception:
        return None

    if output_len <= 0 or duration <= 0:
        return None

    zones = sorted(face_boxes)
    cap = cv2.VideoCapture(str(raw_clip))
    video_fps = cap.get(cv2.CAP_PROP_FPS) or 60
    if not cap.isOpened() or video_fps <= 0:
        return None

    target_fps = output_len / duration
    matrix = np.zeros((output_len, len(zones)), dtype=float)
    previous_rois: dict[int, object] = {}
    output_index = 0
    input_index = 0

    while output_index < output_len:
        ok, img = cap.read()
        if not ok:
            break
        current_t = input_index / video_fps
        wanted_t = output_index / target_fps
        input_index += 1
        if current_t + (0.5 / video_fps) < wanted_t:
            continue

        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        for col, zone in enumerate(zones):
            cx, fy, fw, fh = face_boxes[zone]
            x0 = max(0, int(cx - fw * 0.36))
            x1 = min(gray.shape[1], int(cx + fw * 0.36))
            y0 = max(0, int(fy + fh * 0.46))
            y1 = min(gray.shape[0], int(fy + fh * 0.86))
            if x1 <= x0 or y1 <= y0:
                continue
            roi = cv2.resize(gray[y0:y1, x0:x1], (80, 48))
            if zone in previous_rois:
                diff = cv2.absdiff(roi, previous_rois[zone])
                matrix[output_index, col] = float((diff > 10).sum())
            previous_rois[zone] = roi
        output_index += 1

    cap.release()
    if output_index < max(4, output_len // 4):
        return None
    if output_index < output_len and output_index > 0:
        matrix[output_index:] = matrix[output_index - 1]
    return matrix


def _fixed_face_visibility_matrix(
    raw_clip: Path,
    face_boxes: dict[int, tuple[int, int, int, int]],
    output_len: int,
    duration: float,
) -> object | None:
    """Return a per-face mouth visibility score aligned to TalkNet frames."""
    try:
        import cv2
        import numpy as np
    except Exception:
        return None

    if output_len <= 0 or duration <= 0:
        return None

    zones = sorted(face_boxes)
    cap = cv2.VideoCapture(str(raw_clip))
    video_fps = cap.get(cv2.CAP_PROP_FPS) or 60
    if not cap.isOpened() or video_fps <= 0:
        return None

    target_fps = output_len / duration
    matrix = np.ones((output_len, len(zones)), dtype=float)
    output_index = 0
    input_index = 0

    while output_index < output_len:
        ok, img = cap.read()
        if not ok:
            break
        current_t = input_index / video_fps
        wanted_t = output_index / target_fps
        input_index += 1
        if current_t + (0.5 / video_fps) < wanted_t:
            continue

        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        for col, zone in enumerate(zones):
            cx, fy, fw, fh = face_boxes[zone]
            x0 = max(0, int(cx - fw * 0.34))
            x1 = min(gray.shape[1], int(cx + fw * 0.34))
            y0 = max(0, int(fy + fh * 0.66))
            y1 = min(gray.shape[0], int(fy + fh * 0.98))
            if x1 <= x0 or y1 <= y0:
                continue
            roi = gray[y0:y1, x0:x1]
            dark_ratio = float((roi < 58).sum()) / float(roi.size)
            matrix[output_index, col] = 1.0 - min(1.0, max(0.0, (dark_ratio - 0.22) / 0.38))
        output_index += 1

    cap.release()
    if output_index < max(4, output_len // 4):
        return None
    if output_index < output_len and output_index > 0:
        matrix[output_index:] = matrix[output_index - 1]
    return matrix


def _fixed_face_mouth_detail_matrix(
    raw_clip: Path,
    face_boxes: dict[int, tuple[int, int, int, int]],
    output_len: int,
    duration: float,
    *,
    max_seconds: float = 6.0,
) -> object | None:
    """Return early lower-face edge detail for fixing weak three-panel starts."""
    try:
        import cv2
        import numpy as np
    except Exception:
        return None

    if output_len <= 0 or duration <= 0:
        return None

    zones = sorted(face_boxes)
    cap = cv2.VideoCapture(str(raw_clip))
    video_fps = cap.get(cv2.CAP_PROP_FPS) or 60
    if not cap.isOpened() or video_fps <= 0:
        return None

    target_fps = output_len / duration
    max_output = max(1, min(output_len, int(target_fps * max_seconds)))
    matrix = np.zeros((output_len, len(zones)), dtype=float)
    output_index = 0
    input_index = 0

    while output_index < max_output:
        ok, img = cap.read()
        if not ok:
            break
        current_t = input_index / video_fps
        wanted_t = output_index / target_fps
        input_index += 1
        if current_t + (0.5 / video_fps) < wanted_t:
            continue

        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        for col, zone in enumerate(zones):
            cx, fy, fw, fh = face_boxes[zone]
            x0 = max(0, int(cx - fw * 0.36))
            x1 = min(gray.shape[1], int(cx + fw * 0.36))
            y0 = max(0, int(fy + fh * 0.56))
            y1 = min(gray.shape[0], int(fy + fh * 0.92))
            if x1 <= x0 or y1 <= y0:
                continue
            roi = gray[y0:y1, x0:x1]
            dark_ratio = float((roi < 58).sum()) / float(roi.size)
            visibility = 1.0 - min(1.0, max(0.0, (dark_ratio - 0.22) / 0.38))
            edge_ratio = float((cv2.Canny(roi, 50, 150) > 0).sum()) / float(roi.size)
            matrix[output_index, col] = edge_ratio * visibility
        output_index += 1

    cap.release()
    if output_index < max(4, max_output // 3):
        return None
    if output_index < max_output and output_index > 0:
        matrix[output_index:max_output] = matrix[output_index - 1]
    return matrix


def _build_segments_from_talknet_scores(
    scores,
    duration: float,
    motion_scores=None,
    mouth_visibility=None,
    mouth_detail=None,
    face_boxes: dict[int, tuple[int, int, int, int]] | None = None,
    src_h: int | None = None,
) -> list[tuple[float, float, int]]:
    import numpy as np

    if scores.size == 0 or len(scores.shape) != 2 or scores.shape[1] < 2:
        return []

    n_zones = int(scores.shape[1])
    fps = 25
    med = np.median(scores, axis=0)
    mad = np.median(np.abs(scores - med), axis=0) + 1e-6
    zscores = (scores - med) / mad
    smoothed = np.vstack([
        _smooth_median(zscores[:, z], fps)
        for z in range(n_zones)
    ]).T
    raw_smoothed = np.zeros_like(scores)
    raw_half_window = 13 // 2
    for i in range(len(scores)):
        raw_smoothed[i] = np.median(
            scores[max(0, i - raw_half_window): min(len(scores), i + raw_half_window + 1)],
            axis=0,
        )

    frame_raw = (
        raw_smoothed - raw_smoothed.mean(axis=1, keepdims=True)
    ) / (raw_smoothed.std(axis=1, keepdims=True) + 1e-6)

    face_reliability = np.ones(n_zones, dtype=float)
    if n_zones >= 4 and face_boxes:
        ordered_faces = [face_boxes[z] for z in sorted(face_boxes) if z in face_boxes]
        if len(ordered_faces) == n_zones:
            median_h = float(np.median([f[3] for f in ordered_faces])) + 1e-6
            for idx, (_cx, fy, _fw, fh) in enumerate(ordered_faces):
                size_ratio = float(fh) / median_h
                size_factor = min(1.0, max(0.45, (size_ratio - 0.45) / 0.35))
                low_factor = 1.0
                if src_h:
                    cy_ratio = (float(fy) + float(fh) / 2) / max(1.0, float(src_h))
                    low_factor -= min(0.30, max(0.0, (cy_ratio - 0.49) / 0.22))
                face_reliability[idx] = max(0.42, min(1.0, size_factor * low_factor))

    if (
        n_zones == 2
        and motion_scores is not None
        and mouth_visibility is not None
        and getattr(motion_scores, "shape", None) == scores.shape
        and getattr(mouth_visibility, "shape", None) == scores.shape
        and float(np.max(motion_scores)) > 0
    ):
        # In two-up layouts a large microphone can hide one speaker's mouth and
        # create false visual activity. Keep the TalkNet signal, but blend in
        # frame-relative mouth motion only where the mouth is actually visible.
        motion_smoothed = np.zeros_like(motion_scores, dtype=float)
        visibility_smoothed = np.zeros_like(mouth_visibility, dtype=float)
        motion_half_window = fps // 2
        for i in range(len(motion_scores)):
            frame_slice = slice(max(0, i - motion_half_window), min(len(motion_scores), i + motion_half_window + 1))
            motion_smoothed[i] = np.median(motion_scores[frame_slice], axis=0)
            visibility_smoothed[i] = np.median(mouth_visibility[frame_slice], axis=0)
        motion_log = np.log1p(motion_smoothed * visibility_smoothed)
        frame_motion = (
            motion_log - motion_log.mean(axis=1, keepdims=True)
        ) / (motion_log.std(axis=1, keepdims=True) + 1e-6)
        visibility_rel = (
            visibility_smoothed - visibility_smoothed.mean(axis=1, keepdims=True)
        ) / (visibility_smoothed.std(axis=1, keepdims=True) + 1e-6)
        smoothed = (
            (smoothed * 0.10)
            + (frame_raw * 0.45)
            + (frame_motion * 0.35)
            + (visibility_rel * 0.10)
        )

    if n_zones >= 4:
        # In four-up interview layouts, one panel can have consistently stronger
        # or weaker TalkNet scores because of lighting, microphone position or
        # face angle. Pure per-panel normalization over-corrects that baseline
        # and can ignore the guest while they speak. Blend in a frame-relative
        # raw score and lower-face motion so sustained speaker evidence wins.
        if (
            motion_scores is not None
            and getattr(motion_scores, "shape", None) == scores.shape
            and float(np.max(motion_scores)) > 0
        ):
            motion_smoothed = np.zeros_like(motion_scores, dtype=float)
            motion_half_window = fps // 2
            for i in range(len(motion_scores)):
                motion_smoothed[i] = np.median(
                    motion_scores[
                        max(0, i - motion_half_window): min(len(motion_scores), i + motion_half_window + 1)
                    ],
                    axis=0,
                )
            motion_log = np.log1p(motion_smoothed)
            frame_motion = (
                motion_log - motion_log.mean(axis=1, keepdims=True)
            ) / (motion_log.std(axis=1, keepdims=True) + 1e-6)
            smoothed = (smoothed * 0.10) + (frame_raw * 0.25) + (frame_motion * 0.65)
        else:
            smoothed = (smoothed * 0.25) + (frame_raw * 0.75)
        smoothed = smoothed - ((1.0 - face_reliability) * 0.45)

    start_win = min(len(smoothed), fps)
    current = int(np.argmax(np.mean(smoothed[:start_win], axis=0)))
    transitions: list[tuple[int, int]] = [(0, current)]
    candidate = None
    candidate_start = 0
    last_switch = 0

    # Talk-show interruptions are common: if we require too much certainty or a
    # long hold, the crop stays on the first speaker while someone else talks
    # over them.  These thresholds still ignore one-off reactions, but let
    # sustained interruptions take the frame quickly.
    margin_threshold = 0.35 if n_zones >= 4 else 0.45
    onset_frames = int(fps * (0.60 if n_zones >= 4 else 0.75))
    min_hold_frames = int(fps * (2.0 if n_zones >= 4 else 2.5))

    for i, row in enumerate(smoothed):
        order = np.argsort(row)
        top = int(order[-1])
        margin = float(row[order[-1]] - row[order[-2]])
        if top == current or margin < margin_threshold:
            candidate = None
            continue
        if candidate != top:
            candidate = top
            candidate_start = i
        if i - candidate_start >= onset_frames and i - last_switch >= min_hold_frames:
            transitions.append((candidate_start, top))
            current = top
            last_switch = i
            candidate = None

    frame_count = len(smoothed)
    segments: list[list[int]] = []
    for idx, (start, zone) in enumerate(transitions):
        end = transitions[idx + 1][0] if idx + 1 < len(transitions) else frame_count
        segments.append([start, end, zone])

    # Merge short islands. A one-second model wobble is worse than a slightly
    # delayed cut, especially for clips intended for social publishing.
    changed = True
    min_segment_frames = int(fps * 1.6)
    while changed and len(segments) > 1:
        changed = False
        merged: list[list[int]] = []
        i = 0
        while i < len(segments):
            start, end, zone = segments[i]
            if end - start < min_segment_frames:
                if merged and i + 1 < len(segments):
                    prev = merged[-1]
                    nxt = segments[i + 1]
                    if prev[2] == nxt[2]:
                        prev[1] = nxt[1]
                        i += 2
                        changed = True
                        continue
                    prev_len = prev[1] - prev[0]
                    next_len = nxt[1] - nxt[0]
                    if prev_len >= next_len:
                        prev[1] = end
                        i += 1
                    else:
                        nxt[0] = start
                        i += 1
                    changed = True
                    continue
                if merged:
                    merged[-1][1] = end
                    i += 1
                    changed = True
                    continue
                if i + 1 < len(segments):
                    segments[i + 1][0] = start
                    i += 1
                    changed = True
                    continue
            merged.append([start, end, zone])
            i += 1
        segments = merged

    # Crosstalk correction: when the first speaker gets interrupted, the model
    # can briefly bounce back to the original speaker because both voices are
    # audible.  If the same interrupter surrounds that return early in the clip,
    # keep the frame on the interrupter until the next clear turn change.
    if n_zones <= 3 and len(segments) >= 4:
        initial_zone = segments[0][2]
        for i in range(1, len(segments) - 1):
            prev_seg = segments[i - 1]
            cur_seg = segments[i]
            next_seg = segments[i + 1]
            surrounded_by_interrupter = (
                prev_seg[2] == next_seg[2]
                and prev_seg[2] != initial_zone
                and cur_seg[2] == initial_zone
            )
            early_return = cur_seg[0] < fps * 25
            plausible_overlap = (cur_seg[1] - cur_seg[0]) <= fps * 16
            if surrounded_by_interrupter and early_return and plausible_overlap:
                cur_seg[2] = prev_seg[2]

        merged = []
        for start, end, zone in segments:
            if merged and merged[-1][2] == zone:
                merged[-1][1] = end
            else:
                merged.append([start, end, zone])
        segments = merged

    if n_zones >= 4 and len(segments) >= 3:
        frame_count = max(1, len(smoothed))
        zone_totals = np.zeros(n_zones, dtype=float)
        for start, end, zone in segments:
            zone_totals[zone] += max(0, end - start)
        dominant_zone = int(np.argmax(zone_totals))
        dominant_share = float(zone_totals[dominant_zone]) / frame_count

        if dominant_share >= 0.58:
            for i in range(1, len(segments) - 1):
                prev_seg = segments[i - 1]
                cur_seg = segments[i]
                next_seg = segments[i + 1]
                start, end, zone = cur_seg
                if zone == dominant_zone:
                    continue
                if prev_seg[2] != dominant_zone or next_seg[2] != dominant_zone:
                    continue

                seg_len = end - start
                window = smoothed[start:end]
                evidence_gap = 0.0
                if len(window):
                    evidence_gap = float(
                        np.mean(window[:, zone]) - np.mean(window[:, dominant_zone])
                    )
                weak_face = bool(face_reliability[zone] < 0.72)

                # Four-up interviews often contain long guest monologues while
                # the other panels nod, gesture, drink mate or look down. Those
                # reactions can create short false active-speaker islands. Keep
                # real turn changes, but bridge brief listener islands when a
                # dominant speaker surrounds them.
                if (
                    seg_len <= int(fps * 2.45)
                    or (weak_face and seg_len <= int(fps * 4.50))
                    or (seg_len <= int(fps * 4.00) and evidence_gap < 0.95)
                ):
                    cur_seg[2] = dominant_zone

            merged = []
            for start, end, zone in segments:
                if merged and merged[-1][2] == zone:
                    merged[-1][1] = end
                else:
                    merged.append([start, end, zone])
            segments = merged

    if n_zones == 3:
        # Preserve short centre-speaker interventions. The centre journalist's
        # mouth is often hidden by the mic, so the normalised score can under-call
        # him during quick replies even when the raw audio-visual score is clearly
        # close to the active panel. These short turns matter in vertical clips.
        center_events: list[list[int]] = []
        event_start = None
        center_median = med[1]
        center_mad = mad[1]
        for i, row in enumerate(raw_smoothed):
            side_top = max(row[0], row[2])
            center_z = (row[1] - center_median) / center_mad
            is_center_turn = row[1] >= side_top - 0.35 and center_z > 0.45
            if is_center_turn and event_start is None:
                event_start = i
            if (not is_center_turn or i == len(raw_smoothed) - 1) and event_start is not None:
                event_end = i if not is_center_turn else i + 1
                if event_end - event_start >= int(fps * 0.45):
                    center_events.append([
                        max(0, event_start - int(fps * 0.10)),
                        min(len(raw_smoothed), event_end + int(fps * 0.15)),
                        1,
                    ])
                event_start = None

        merged_events: list[list[int]] = []
        for start, end, zone in center_events:
            if merged_events and start - merged_events[-1][1] <= int(fps * 0.70):
                merged_events[-1][1] = end
            else:
                merged_events.append([start, end, zone])

        for event_start, event_end, event_zone in merged_events:
            updated: list[list[int]] = []
            for start, end, zone in segments:
                if end <= event_start or start >= event_end:
                    updated.append([start, end, zone])
                    continue
                if start < event_start:
                    updated.append([start, event_start, zone])
                updated.append([max(start, event_start), min(end, event_end), event_zone])
                if end > event_end:
                    updated.append([event_end, end, zone])
            segments = updated

    if (
        n_zones == 3
        and segments
        and mouth_detail is not None
        and getattr(mouth_detail, "shape", None) == scores.shape
    ):
        # TalkNet can occasionally give the first seconds to the wrong side
        # panel with a weak margin. Use early visible-mouth detail as a tiebreak,
        # but only for short lateral false starts so centre mic occlusion is not
        # punished in normal turns.
        current_zone = int(segments[0][2])
        detail_window = min(len(mouth_detail), int(fps * 3.2))
        if detail_window >= int(fps * 0.8) and current_zone in (0, 2):
            detail_mean = np.mean(mouth_detail[:detail_window], axis=0)
            best_zone = int(np.argmax(detail_mean))
            raw_mean = np.mean(raw_smoothed[:detail_window], axis=0)
            raw_order = np.argsort(raw_mean)
            raw_margin = float(raw_mean[raw_order[-1]] - raw_mean[raw_order[-2]])
            first_len = int(segments[0][1] - segments[0][0])
            visual_beats_current = (
                best_zone in (0, 2)
                and best_zone != current_zone
                and float(detail_mean[best_zone]) >= 0.055
                and float(detail_mean[best_zone]) >= float(detail_mean[current_zone]) * 1.28
            )
            visual_confirms_current = (
                best_zone == current_zone
                and float(detail_mean[best_zone]) >= 0.055
            )
            if (
                (visual_beats_current or visual_confirms_current)
                and raw_margin < 0.65
                and first_len <= int(fps * 4.2)
            ):
                if visual_beats_current:
                    segments[0][2] = best_zone
                for idx in range(1, min(len(segments) - 1, 4)):
                    next_clear_is_best = any(
                        future[2] == best_zone
                        for future in segments[idx + 1:min(len(segments), idx + 4)]
                    )
                    if (
                        segments[idx][2] != best_zone
                        and next_clear_is_best
                        and segments[idx][1] - segments[idx][0] <= int(fps * 1.85)
                    ):
                        segments[idx][2] = best_zone

    merged = []
    for start, end, zone in segments:
        if end <= start:
            continue
        if merged and merged[-1][2] == zone:
            merged[-1][1] = end
        else:
            merged.append([start, end, zone])
    segments = merged

    return [
        (round(start / fps, 1), round(min(end / fps, duration), 1), zone)
        for start, end, zone in segments
        if end > start
    ]


def _detect_talknet_fixed_timeline(
    raw_clip: Path,
    face_boxes: dict[int, tuple[int, int, int, int]],
    src_w: int,
    src_h: int,
    duration: float,
    *,
    layout: str = "panel3",
) -> list[dict] | None:
    """
    Use the local TalkNet active-speaker model on fixed per-panel face crops.

    The full TalkNet demo performs neural face detection on every frame, which
    is too slow for the daily workflow.  In this show the three panel positions
    are fixed, so we reuse the already detected face boxes and only run the
    audio-visual active-speaker model.
    """
    zones = sorted(face_boxes)
    if len(zones) < 2:
        return None

    model = _get_talknet_model()
    if model is None:
        return None

    try:
        import cv2
        import numpy as np
        import torch
        import python_speech_features
        from scipy.io import wavfile
    except Exception:
        return None

    target_fps = 25
    try:
        cache_dir = raw_clip.parent / ".talknet_cache"
        cache_dir.mkdir(exist_ok=True)
        face_cache_key = json.dumps(
            {str(k): [int(vv) for vv in v] for k, v in sorted(face_boxes.items())},
            sort_keys=True,
        )
        cache_path = cache_dir / f"{raw_clip.stem}_scores_v1.npz"
        score_matrix = None
        if cache_path.exists():
            try:
                cached = np.load(cache_path, allow_pickle=False)
                if (
                    int(cached["raw_mtime"]) == int(raw_clip.stat().st_mtime)
                    and int(cached["raw_size"]) == int(raw_clip.stat().st_size)
                    and str(cached["face_key"]) == face_cache_key
                ):
                    score_matrix = cached["scores"]
                    print("    → TalkNet fijo: usando scores cacheados")
            except Exception:
                score_matrix = None

        if score_matrix is not None:
            motion_matrix = (
                _fixed_face_motion_matrix(raw_clip, face_boxes, len(score_matrix), duration)
                if layout in {"panel2", "panel3", "panel4"} else None
            )
            visibility_matrix = (
                _fixed_face_visibility_matrix(raw_clip, face_boxes, len(score_matrix), duration)
                if layout in {"panel2", "panel3"} else None
            )
            mouth_detail_matrix = (
                _fixed_face_mouth_detail_matrix(raw_clip, face_boxes, len(score_matrix), duration)
                if layout == "panel3" else None
            )
            speaker_segments = _build_segments_from_talknet_scores(
                score_matrix,
                duration,
                motion_scores=motion_matrix,
                mouth_visibility=visibility_matrix,
                mouth_detail=mouth_detail_matrix,
                face_boxes=face_boxes,
                src_h=src_h,
            )
            if not speaker_segments:
                return None
            timeline = []
            if layout == "panel2":
                crop_for_zone = _two_panel_crop_for_zone
            elif layout == "panel4":
                crop_for_zone = lambda w, h, zone: _four_panel_crop_for_zone(
                    w, h, zone, face_boxes.get(zone)
                )
            else:
                crop_for_zone = _panel_crop_for_zone
            for start, end, score_zone in speaker_segments:
                zone = zones[score_zone]
                timeline.append({
                    "t_start": start,
                    "t_end": end,
                    "layout": layout,
                    **crop_for_zone(src_w, src_h, zone),
                })
            timeline[0]["t_start"] = 0.0
            timeline[-1]["t_end"] = duration
            return timeline

        with tempfile.TemporaryDirectory() as tmp:
            tmp_path = Path(tmp)
            crop_dir = tmp_path / "pycrop"
            crop_dir.mkdir()
            audio_path = crop_dir / "audio.wav"
            subprocess.run(
                [
                    FFMPEG_BIN, "-y", "-v", "error", "-i", str(raw_clip),
                    "-ac", "1", "-vn", "-acodec", "pcm_s16le", "-ar", "16000",
                    str(audio_path),
                ],
                check=True,
            )

            cap = cv2.VideoCapture(str(raw_clip))
            video_fps = cap.get(cv2.CAP_PROP_FPS) or 60
            if not cap.isOpened() or video_fps <= 0:
                return None

            fourcc = cv2.VideoWriter_fourcc(*"XVID")
            writers = {}
            crop_rects = {
                z: _talknet_crop_rect(src_w, src_h, face_boxes[z])
                for z in zones
            }
            for z in zones:
                writers[z] = cv2.VideoWriter(
                    str(crop_dir / f"{z:05d}.avi"),
                    fourcc,
                    target_fps,
                    (224, 224),
                )
                shutil.copyfile(audio_path, crop_dir / f"{z:05d}.wav")

            frame_count = int(duration * target_fps)
            output_index = 0
            input_index = 0
            while output_index < frame_count:
                ok, img = cap.read()
                if not ok:
                    break
                current_t = input_index / video_fps
                wanted_t = output_index / target_fps
                input_index += 1
                if current_t + (0.5 / video_fps) < wanted_t:
                    continue
                for z, writer in writers.items():
                    x, y, w, h = crop_rects[z]
                    x1 = max(0, x)
                    y1 = max(0, y)
                    x2 = min(src_w, x + w)
                    y2 = min(src_h, y + h)
                    crop = np.full((h, w, 3), 110, dtype=np.uint8)
                    dx = x1 - x
                    dy = y1 - y
                    if x2 > x1 and y2 > y1:
                        crop[dy:dy + (y2 - y1), dx:dx + (x2 - x1)] = img[y1:y2, x1:x2]
                    writer.write(cv2.resize(crop, (224, 224)))
                output_index += 1
            cap.release()
            for writer in writers.values():
                writer.release()

            scores_by_zone = []
            for z in zones:
                _, audio = wavfile.read(str(crop_dir / f"{z:05d}.wav"))
                audio_feature = python_speech_features.mfcc(
                    audio,
                    16000,
                    numcep=13,
                    winlen=0.025,
                    winstep=0.010,
                )
                video = cv2.VideoCapture(str(crop_dir / f"{z:05d}.avi"))
                video_feature = []
                while video.isOpened():
                    ret, frame = video.read()
                    if not ret:
                        break
                    face = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
                    face = cv2.resize(face, (224, 224))[56:168, 56:168]
                    video_feature.append(face)
                video.release()
                if not video_feature:
                    return None
                video_feature = np.array(video_feature)
                length = min(
                    (audio_feature.shape[0] - audio_feature.shape[0] % 4) / 100,
                    video_feature.shape[0] / target_fps,
                )
                if length <= 1:
                    return None
                audio_feature = audio_feature[:int(round(length * 100)), :]
                video_feature = video_feature[:int(round(length * target_fps)), :, :]

                zone_scores = []
                duration_window = 2
                batch_count = int(np.ceil(length / duration_window))
                with torch.no_grad():
                    for i in range(batch_count):
                        input_a = torch.FloatTensor(
                            audio_feature[
                                i * duration_window * 100:(i + 1) * duration_window * 100,
                                :,
                            ]
                        ).unsqueeze(0).to(model.device)
                        input_v = torch.FloatTensor(
                            video_feature[
                                i * duration_window * target_fps:(i + 1) * duration_window * target_fps,
                                :,
                                :,
                            ]
                        ).unsqueeze(0).to(model.device)
                        embed_a = model.model.forward_audio_frontend(input_a)
                        embed_v = model.model.forward_visual_frontend(input_v)
                        embed_a, embed_v = model.model.forward_cross_attention(embed_a, embed_v)
                        out = model.model.forward_audio_visual_backend(embed_a, embed_v)
                        zone_scores.extend(model.lossAV.forward(out, labels=None))
                scores_by_zone.append(np.array(zone_scores, dtype=float))

            min_len = min(len(s) for s in scores_by_zone)
            if min_len < target_fps:
                return None
            score_matrix = np.vstack([s[:min_len] for s in scores_by_zone]).T
            np.savez(
                cache_path,
                scores=score_matrix,
                raw_mtime=int(raw_clip.stat().st_mtime),
                raw_size=int(raw_clip.stat().st_size),
                face_key=face_cache_key,
            )
            motion_matrix = (
                _fixed_face_motion_matrix(raw_clip, face_boxes, len(score_matrix), duration)
                if layout in {"panel2", "panel3", "panel4"} else None
            )
            visibility_matrix = (
                _fixed_face_visibility_matrix(raw_clip, face_boxes, len(score_matrix), duration)
                if layout in {"panel2", "panel3"} else None
            )
            mouth_detail_matrix = (
                _fixed_face_mouth_detail_matrix(raw_clip, face_boxes, len(score_matrix), duration)
                if layout == "panel3" else None
            )
            speaker_segments = _build_segments_from_talknet_scores(
                score_matrix,
                duration,
                motion_scores=motion_matrix,
                mouth_visibility=visibility_matrix,
                mouth_detail=mouth_detail_matrix,
                face_boxes=face_boxes,
                src_h=src_h,
            )
            if not speaker_segments:
                return None

            timeline = []
            if layout == "panel2":
                crop_for_zone = _two_panel_crop_for_zone
            elif layout == "panel4":
                crop_for_zone = lambda w, h, zone: _four_panel_crop_for_zone(
                    w, h, zone, face_boxes.get(zone)
                )
            else:
                crop_for_zone = _panel_crop_for_zone
            for start, end, score_zone in speaker_segments:
                zone = zones[score_zone]
                timeline.append({
                    "t_start": start,
                    "t_end": end,
                    "layout": layout,
                    **crop_for_zone(src_w, src_h, zone),
                })
            timeline[0]["t_start"] = 0.0
            timeline[-1]["t_end"] = duration
            return timeline
    except Exception as exc:
        print(f"    → TalkNet fijo no disponible para este clip ({exc}); uso detector liviano")
        return None


def detect_active_speaker_timeline(raw_clip: Path) -> list[dict] | None:
    """
    Build a per-speaker dynamic zoom timeline using face-detection-based
    mouth-motion tracking.

    The broadcast always has exactly 3 journalists at FIXED horizontal positions
    (left / centre / right thirds of the frame).  The algorithm:

      1. Extract frames at 6 fps for fine temporal resolution.
      2. Detect faces in a sample of frames to establish stable mouth ROIs
         for each of the 3 zones (using OpenCV Haar cascade).
      3. For each consecutive frame pair, compute motion ONLY within the
         mouth ROI of each face (lower 40% of face bbox).  This ignores
         hand gestures, head nods, and body movements.
      4. Normalise each zone's mouth energy by its clip-wide mean.
      5. Apply incumbent penalty + dominance ratio to prevent false switches.
      6. Use onset-based transitions with minimum hold time.
      7. Map each segment to one of 3 fixed crop positions.
    """
    try:
        import cv2
        import numpy as np
    except ImportError:
        return None

    # ── Probe clip ────────────────────────────────────────────────────────────
    probe = subprocess.run([FFMPEG_BIN, "-i", str(raw_clip)], capture_output=True, text=True)
    dim_m = re.search(r"(\d{3,4})x(\d{3,4})", probe.stderr)
    dur_m = re.search(r"Duration:\s*(\d+):(\d+):([\d.]+)", probe.stderr)
    if not dim_m or not dur_m:
        return None
    src_w = int(dim_m.group(1))
    src_h = int(dim_m.group(2))
    duration = (
        int(dur_m.group(1)) * 3600
        + int(dur_m.group(2)) * 60
        + float(dur_m.group(3))
    )

    # ── Fixed 3-zone crop positions ───────────────────────────────────────────
    crop_h = int(src_h * PANEL_CROP_HEIGHT_RATIO)
    crop_w = int(crop_h * 9 / 16)
    if crop_w > src_w:
        crop_w = src_w
        crop_h = int(crop_w * 16 / 9)

    zone_w = src_w // 3
    zone_centers = [
        zone_w // 2,
        zone_w + zone_w // 2,
        2 * zone_w + zone_w // 2,
    ]

    def zone_to_crop(zone_idx: int) -> dict:
        return _panel_crop_for_zone(src_w, src_h, zone_idx)

    # ── Tuneable constants ────────────────────────────────────────────────────
    FPS               = 6       # frame extraction rate
    MOTION_THRESHOLD  = 250.0   # minimum speech-pixel count to register as motion
    INCUMBENT_PENALTY = 0.85    # multiplier on current zone's normalised score
    ONSET_FRAMES      = 7       # consecutive frames needed to trigger a switch (~1.2s at 6fps)
    MIN_HOLD          = 4.0     # seconds before allowing another switch
    DOMINANCE_RATIO   = 2.0     # new zone must beat incumbent by this factor
    ABSOLUTE_RATIO    = 1.0     # and also match/exceed raw mouth activity
    MIN_ABS_SHARE     = 0.55    # ignore low-energy relative spikes from quiet panels
    STRONG_SWITCH_RAW = 1.25    # allow switch through weak Haar visibility on strong speech
    STRONG_SWITCH_MIN_SHARE = 0.42

    with tempfile.TemporaryDirectory() as tmp_dir:
        fdir = Path(tmp_dir)

        # ── Step 1: Extract frames ───────────────────────────────────────────
        max_frames = min(int(duration * FPS) + 4, 600)
        subprocess.run(
            [FFMPEG_BIN, "-i", str(raw_clip),
             "-vf", f"fps={FPS}", "-q:v", "5", "-vframes", str(max_frames),
             str(fdir / "f%04d.jpg")],
            capture_output=True,
        )
        frame_files = sorted(fdir.glob("f*.jpg"))
        if len(frame_files) < 4:
            return None

        # ── Step 2: Detect faces and establish mouth ROIs ────────────────────
        # Haar frontal-face detections are fast enough for this local workflow,
        # but they can produce false positives on microphones, hands, shirts or
        # sponsor graphics.  Use several face cascades, then validate candidates
        # with an eye detector before trusting them as a mouth ROI.
        face_cascade = cv2.CascadeClassifier(
            cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
        )
        face_cascades = [
            face_cascade,
            cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_alt2.xml"),
            cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_alt.xml"),
            cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_profileface.xml"),
        ]
        eye_cascades = [
            cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye_tree_eyeglasses.xml"),
            cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml"),
        ]

        def panel_face_candidates(
            gray,
            *,
            min_size: tuple[int, int],
            require_eyes: bool,
        ) -> list[tuple[int, int, int, int, int]]:
            candidates: list[tuple[int, int, int, int, int]] = []
            seen: list[tuple[int, int, int, int]] = []
            for cascade in face_cascades:
                if cascade.empty():
                    continue
                faces = cascade.detectMultiScale(
                    gray, scaleFactor=1.05, minNeighbors=4, minSize=min_size
                )
                for (fx, fy, fw, fh) in faces:
                    cx = fx + fw // 2
                    cy = fy + fh // 2
                    # In the split-panel studio layout the usable faces live in
                    # the upper/middle half.  Lower detections are usually hands,
                    # microphones, hoodies or sponsor marks.
                    if cy > src_h * 0.62 or fy > src_h * 0.50:
                        continue
                    if fw < src_w * 0.045 or fh < src_h * 0.07:
                        continue

                    duplicate = False
                    for sx, sy, sw, sh in seen:
                        if abs(cx - (sx + sw // 2)) < max(fw, sw) * 0.28 and abs(cy - (sy + sh // 2)) < max(fh, sh) * 0.28:
                            duplicate = True
                            break
                    if duplicate:
                        continue
                    seen.append((fx, fy, fw, fh))

                    upper = gray[fy:fy + int(fh * 0.62), fx:fx + fw]
                    eye_count = 0
                    if upper.size:
                        for eye_cascade in eye_cascades:
                            if eye_cascade.empty():
                                continue
                            eyes = eye_cascade.detectMultiScale(
                                upper,
                                scaleFactor=1.05,
                                minNeighbors=3,
                                minSize=(max(14, fw // 10), max(10, fh // 14)),
                            )
                            eye_count = max(eye_count, len(eyes))

                    if require_eyes and eye_count <= 0:
                        continue
                    candidates.append((fx, fy, fw, fh, min(eye_count, 2)))
            return candidates

        panel_flags: list[bool] = []
        four_panel_flags: list[bool] = []
        two_panel_flags: list[bool] = []
        for frame_path in frame_files:
            img = cv2.imread(str(frame_path))
            if img is None:
                panel_flags.append(False)
                four_panel_flags.append(False)
                two_panel_flags.append(False)
            else:
                panel_flags.append(_is_split_panel_frame(img, src_w))
                four_panel_flags.append(_is_four_panel_frame(img, src_w))
                two_panel_flags.append(_is_two_panel_frame(img, src_w))

        panel_indices = [i for i, is_panel in enumerate(panel_flags) if is_panel]
        four_panel_indices = [i for i, is_panel in enumerate(four_panel_flags) if is_panel]
        two_panel_indices = [i for i, is_panel in enumerate(two_panel_flags) if is_panel]
        panel_ratio = len(panel_indices) / len(frame_files)
        print(f"    → Layout panel dividido: {len(panel_indices)}/{len(frame_files)} frames ({panel_ratio:.0%})")

        def fixed_panel_talknet_timeline(
            fixed_indices: list[int],
            panel_count: int,
            layout: str,
        ) -> list[dict] | None:
            zone_centers_fixed = _panel_zone_centers(src_w, panel_count)
            zone_w_fixed = src_w / panel_count
            sample_indices = np.array(
                [
                    fixed_indices[int(round(i))]
                    for i in np.linspace(0, len(fixed_indices) - 1, min(12, len(fixed_indices)))
                ],
                dtype=int,
            )
            faces_by_zone: dict[int, list[tuple[int, int, int, int]]] = {
                z: [] for z in range(panel_count)
            }
            separators = [src_w * i / panel_count for i in range(1, panel_count)]
            for si in sample_indices:
                img = cv2.imread(str(frame_files[si]))
                if img is None:
                    continue
                gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                faces = panel_face_candidates(
                    gray,
                    min_size=(max(60, src_w // 24), max(80, src_h // 13)),
                    require_eyes=True,
                )
                candidates_by_zone: dict[int, list[tuple[int, int, int, int, int]]] = {
                    z: [] for z in range(panel_count)
                }
                for (fx, fy, fw, fh, eyes) in faces:
                    cx = fx + fw // 2
                    if any(abs(cx - sep) < src_w * 0.025 for sep in separators):
                        continue
                    candidates_by_zone[_panel_zone_for_x_count(src_w, cx, panel_count)].append((fx, fy, fw, fh, eyes))

                for z, candidates in candidates_by_zone.items():
                    if not candidates:
                        continue

                    def face_score(face: tuple[int, int, int, int, int]) -> tuple[float, float]:
                        fx, fy, fw, fh, eyes = face
                        cx = fx + fw / 2
                        cy = fy + fh / 2
                        center_dist = abs(cx - zone_centers_fixed[z]) / max(1, zone_w_fixed)
                        high_penalty = max(0.0, (src_h * 0.24 - cy) / max(1, src_h * 0.24))
                        low_penalty = max(0.0, (cy - src_h * 0.60) / max(1, src_h * 0.40))
                        eye_bonus = eyes * 0.35
                        return (center_dist + high_penalty + low_penalty - eye_bonus, -fw * fh)

                    fx, fy, fw, fh, _eyes = min(candidates, key=face_score)
                    faces_by_zone[z].append((fx + fw // 2, fy, fw, fh))

            face_boxes: dict[int, tuple[int, int, int, int]] = {}
            for z in range(panel_count):
                zone_faces = faces_by_zone[z]
                if not zone_faces:
                    continue
                face_boxes[z] = (
                    int(np.median([f[0] for f in zone_faces])),
                    int(np.median([f[1] for f in zone_faces])),
                    int(np.median([f[2] for f in zone_faces])),
                    int(np.median([f[3] for f in zone_faces])),
                )
                cx, fy, fw, fh = face_boxes[z]
                print(f"    → Cara panel {z + 1}/{panel_count}: cx={cx}, y={fy}, {fw}x{fh}px")

            if set(face_boxes) != set(range(panel_count)):
                print(f"    → Detecté {len(face_boxes)}/{panel_count} caras del layout; no uso TalkNet fijo")
                return None

            talknet_segments = _detect_talknet_fixed_timeline(
                raw_clip,
                face_boxes,
                src_w,
                src_h,
                duration,
                layout=layout,
            )
            if not talknet_segments:
                return None

            zone_names_by_count = {
                2: ["izq", "der"],
                4: ["izq", "ctr-izq", "ctr-der", "der"],
            }
            zone_names_fixed = zone_names_by_count.get(
                panel_count,
                [f"panel {z + 1}" for z in range(panel_count)],
            )
            print("    → TalkNet fijo: speaker detectado con audio+video")
            print(f"    → {len(talknet_segments)} segmento(s) con zoom dinámico:")
            for seg in talknet_segments:
                if panel_count == 2:
                    zone_idx = _two_panel_zone_for_x(src_w, seg["x"] + seg["w"] // 2)
                else:
                    zone_idx = _panel_zone_for_x_count(src_w, seg["x"] + seg["w"] // 2, panel_count)
                print(
                    f"       {seg['t_start']:.1f}s → {seg['t_end']:.1f}s  "
                    f"{zone_names_fixed[zone_idx]}"
                )
            return talknet_segments

        # If there are no stable split-panel frames, this is a close-up/single
        # camera clip or the two-panel show layout.  Try the two-panel active
        # speaker path before falling back to static face-aware zoom.
        if len(panel_indices) < 4:
            if len(four_panel_indices) >= 4:
                print(f"    → Layout panel cuádruple: {len(four_panel_indices)}/{len(frame_files)} frames")
                four_timeline = fixed_panel_talknet_timeline(four_panel_indices, 4, "panel4")
                if four_timeline:
                    return four_timeline

            if len(two_panel_indices) >= 4:
                print(f"    → Layout panel doble: {len(two_panel_indices)}/{len(frame_files)} frames")
                two_timeline = fixed_panel_talknet_timeline(two_panel_indices, 2, "panel2")
                if two_timeline:
                    return two_timeline

            print("    → No hay suficientes frames de panel dividido")
            return None

        # Track whether each panel still has a usable, visible face per frame.
        # Mouth-motion alone can be fooled by someone looking down at a phone,
        # a hand crossing the mouth ROI, or microphone movement.  A new speaker
        # candidate must have a visible face during the onset before we cut to it.
        face_visible_zones: list[set[int]] = []
        visibility_min_size = (src_w // 16, src_h // 10)
        for frame_path, is_panel in zip(frame_files, panel_flags):
            zones: set[int] = set()
            if is_panel:
                img = cv2.imread(str(frame_path))
                if img is not None:
                    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                    for (fx, fy, fw, fh, _eyes) in panel_face_candidates(
                        gray,
                        min_size=visibility_min_size,
                        require_eyes=True,
                    ):
                        zones.add(_panel_zone_for_x(src_w, fx + fw // 2))
            face_visible_zones.append(zones)

        def visible_ratio(frame_idx: int, zone_idx: int, window: int) -> float:
            start = max(0, frame_idx - window + 1)
            end = min(len(face_visible_zones), frame_idx + 1)
            panel_count = 0
            visible_count = 0
            for j in range(start, end):
                if not panel_flags[j]:
                    continue
                panel_count += 1
                if zone_idx in face_visible_zones[j]:
                    visible_count += 1
            if panel_count <= 0:
                return 0.0
            return visible_count / panel_count

        # Sample only split-panel frames to find stable face positions.  Close-up
        # shots often create false Haar detections in hands/wall texture and must
        # not define the left/centre/right mouth ROIs.
        sample_indices = np.array(
            [
                panel_indices[int(round(i))]
                for i in np.linspace(0, len(panel_indices) - 1, min(10, len(panel_indices)))
            ],
            dtype=int,
        )
        all_faces = []
        for si in sample_indices:
            img = cv2.imread(str(frame_files[si]))
            if img is None:
                continue
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            faces = panel_face_candidates(
                gray,
                min_size=(src_w // 14, src_h // 10),
                require_eyes=True,
            )
            faces_by_zone: dict[int, list[tuple[int, int, int, int, int]]] = {0: [], 1: [], 2: []}
            for (fx, fy, fw, fh, eyes) in faces:
                cx = fx + fw // 2
                faces_by_zone[_panel_zone_for_x(src_w, cx)].append((fx, fy, fw, fh, eyes))

            # Haar can return duplicate/partial faces in the same panel,
            # especially when a microphone covers the mouth.  Keep one face per
            # panel per sampled frame: the one closest to the fixed presenter
            # centre, with a small penalty for unusually low detections.
            for z, candidates in faces_by_zone.items():
                if not candidates:
                    continue

                def face_score(face: tuple[int, int, int, int, int]) -> tuple[float, float]:
                    fx, fy, fw, fh, eyes = face
                    cx = fx + fw / 2
                    cy = fy + fh / 2
                    center_dist = abs(cx - zone_centers[z]) / max(1, zone_w)
                    low_penalty = max(0.0, (cy - src_h * 0.54) / max(1, src_h * 0.46))
                    eye_bonus = eyes * 0.35
                    return (center_dist + low_penalty - eye_bonus, -fw * fh)

                fx, fy, fw, fh, _eyes = min(candidates, key=face_score)
                all_faces.append((fx + fw // 2, fy, fw, fh))  # (center_x, y, w, h)

        if len(all_faces) < 3:
            print(f"    → Solo {len(all_faces)} detecciones de cara, insuficiente")
            return None

        # Cluster faces into 3 zones by horizontal center
        face_xs = np.array([f[0] for f in all_faces])
        zone_assignments = np.digitize(face_xs, [zone_w, 2 * zone_w]) # 0=izq, 1=ctr, 2=der

        # Build median mouth/head ROIs per zone.  Speech should move the lower
        # face more than the upper face; head turns move both and are discounted.
        mouth_rois: dict[int, tuple[int, int, int, int] | None] = {}
        head_rois: dict[int, tuple[int, int, int, int] | None] = {}
        face_boxes: dict[int, tuple[int, int, int, int]] = {}
        available_zones: list[int] = []
        for z in range(3):
            zone_faces = [all_faces[i] for i in range(len(all_faces)) if zone_assignments[i] == z]
            if not zone_faces:
                print(f"    → No se detectaron caras en zona {z}; se ignora para tracking")
                mouth_rois[z] = None
                head_rois[z] = None
                continue
            available_zones.append(z)
            med_cx = int(np.median([f[0] for f in zone_faces]))
            med_y  = int(np.median([f[1] for f in zone_faces]))
            med_w  = int(np.median([f[2] for f in zone_faces]))
            med_h  = int(np.median([f[3] for f in zone_faces]))
            face_boxes[z] = (med_cx, med_y, med_w, med_h)
            # Keep the mouth ROI inside the detected face. Extending below the
            # chin catches microphones, hands and phones, which caused false
            # switches to panelists looking down.
            mouth_y1 = med_y + int(med_h * 0.52)
            mouth_y2 = min(med_y + int(med_h * 0.88), src_h)
            mouth_x1 = max(0, med_cx - int(med_w * 0.30))
            mouth_x2 = min(src_w, med_cx + int(med_w * 0.30))
            mouth_rois[z] = (mouth_x1, mouth_y1, mouth_x2, mouth_y2)
            head_y1 = max(0, med_y + int(med_h * 0.15))
            head_y2 = min(src_h, med_y + int(med_h * 0.50))
            head_x1 = mouth_x1
            head_x2 = mouth_x2
            head_rois[z] = (head_x1, head_y1, head_x2, head_y2)

        if not available_zones:
            print("    → No se detectaron caras utilizables en panel")
            return None

        zone_names = ["izq", "ctr", "der"]
        for z in range(3):
            r = mouth_rois[z]
            if r is None:
                continue
            print(f"    → Boca {zone_names[z]}: ({r[0]},{r[1]})-({r[2]},{r[3]}) "
                  f"[{r[2]-r[0]}x{r[3]-r[1]}px]")

        talknet_segments = _detect_talknet_fixed_timeline(
            raw_clip,
            face_boxes,
            src_w,
            src_h,
            duration,
        )
        if talknet_segments:
            print("    → TalkNet fijo: speaker detectado con audio+video")
            print(f"    → {len(talknet_segments)} segmento(s) con zoom dinámico:")
            for seg in talknet_segments:
                zone_idx = _panel_zone_for_x(src_w, seg["x"] + seg["w"] // 2)
                print(
                    f"       {seg['t_start']:.1f}s → {seg['t_end']:.1f}s  "
                    f"{zone_names[zone_idx]}"
                )
            return talknet_segments

        # ── Step 3: Collect per-frame MOUTH energy ───────────────────────────
        # Only count pixels with MODERATE motion (speech range 8-80).
        # This filters out:
        #   - static pixels (< 8): no motion / noise
        #   - large object motion (> 80): glass, hand crossing mouth area
        # Speaking = many pixels with small motion; drinking = few pixels with huge motion
        SPEECH_LO = 8    # minimum pixel diff to count as motion
        SPEECH_HI = 80   # maximum pixel diff (above = object, not lips)

        all_e: list[tuple[float, list[float], bool]] = []
        for idx in range(len(frame_files) - 1):
            t = idx / FPS
            img1 = cv2.imread(str(frame_files[idx]))
            img2 = cv2.imread(str(frame_files[idx + 1]))
            if img1 is None or img2 is None:
                continue
            is_panel = panel_flags[idx] and panel_flags[idx + 1]
            g1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
            g2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
            e = []
            for z in range(3):
                if is_panel and mouth_rois[z] is not None:
                    x1, y1, x2, y2 = mouth_rois[z]
                    roi1 = g1[y1:y2, x1:x2]
                    roi2 = g2[y1:y2, x1:x2]
                    diff = cv2.absdiff(roi1, roi2).astype(np.float32)
                    diff = cv2.GaussianBlur(diff, (7, 7), 0)
                    # Count pixels in speech motion range (not object motion)
                    speech_mask = (diff >= SPEECH_LO) & (diff <= SPEECH_HI)
                    mouth_density = float(speech_mask.sum()) / max(1, speech_mask.size)
                    head_density = 0.0
                    head_roi = head_rois.get(z)
                    if head_roi is not None:
                        hx1, hy1, hx2, hy2 = head_roi
                        href1 = g1[hy1:hy2, hx1:hx2]
                        href2 = g2[hy1:hy2, hx1:hx2]
                        hdiff = cv2.absdiff(href1, href2).astype(np.float32)
                        hdiff = cv2.GaussianBlur(hdiff, (7, 7), 0)
                        head_mask = (hdiff >= SPEECH_LO) & (hdiff <= SPEECH_HI)
                        head_density = float(head_mask.sum()) / max(1, head_mask.size)
                    speech_density = max(0.0, mouth_density - head_density * 0.75)
                    e.append(speech_density * speech_mask.size)
                else:
                    e.append(0.0)
            all_e.append((t, e, is_panel))

        if len(all_e) < 4:
            return None

        # ── Step 3b: Temporal smoothing to filter transient events ───────────
        # A smile creates a 1-2 frame spike then settles. Speaking creates
        # sustained motion across many frames.  Replace each frame's energy
        # with the MINIMUM of a sliding window — only sustained motion survives.
        SMOOTH_WIN = 3  # window size in frames (~0.5s at 6fps)
        smoothed: list[tuple[float, list[float], bool]] = []
        for i in range(len(all_e)):
            t, _e, is_panel = all_e[i]
            win_start = max(0, i - SMOOTH_WIN // 2)
            win_end   = min(len(all_e), i + SMOOTH_WIN // 2 + 1)
            se = []
            for z in range(3):
                # Use median of window — filters out isolated spikes (smiles)
                # while preserving sustained activity (speech)
                vals = [all_e[j][1][z] for j in range(win_start, win_end) if all_e[j][2]]
                if not vals:
                    vals = [0.0]
                se.append(float(np.median(vals)))
            smoothed.append((t, se, is_panel))
        all_e = smoothed

        # ── Step 4: Normalise by zone mean ───────────────────────────────────
        panel_energy = [e for _, e, is_panel in all_e if is_panel]
        if len(panel_energy) < 4:
            print("    → Muy poca energía de panel dividido")
            return None

        zone_means = [
            max(float(np.mean([e[z] for e in panel_energy])), 1.0)
            for z in range(3)
        ]

        # ── Step 5: Raw classification (normalised + incumbent penalty) ──────
        # Smart start: pick the zone with the strongest absolute mouth energy in
        # the first seconds.  Normalised scores are great for later switches, but
        # at clip start they can overvalue a quiet panel whose mean is tiny.
        startup_energy_items = [e for _, e, is_panel in all_e if is_panel]
        startup_frames = min(FPS * 3, len(startup_energy_items))
        startup_abs = [0.0, 0.0, 0.0]
        startup_norm = [0.0, 0.0, 0.0]
        for e in startup_energy_items[:startup_frames]:
            for z in range(3):
                startup_abs[z] += e[z]
                startup_norm[z] += e[z] / zone_means[z]
        if max(startup_abs[z] for z in available_zones) <= 0 and 1 in available_zones:
            current_zone = 1
        else:
            current_zone = max(available_zones, key=lambda z: (startup_abs[z], startup_norm[z]))
        raw_states: list[tuple[float, int, bool]] = []
        for t, e, is_panel in all_e:
            if not is_panel:
                raw_states.append((t, 1, False))
                continue
            if sum(e) < MOTION_THRESHOLD:
                raw_states.append((t, current_zone, True))
                continue
            norm = [e[z] / zone_means[z] for z in range(3)]
            for z in range(3):
                if z not in available_zones:
                    norm[z] = -1.0
            norm[current_zone] *= INCUMBENT_PENALTY
            winner = int(np.argmax(norm))
            # Require dominance in both normalised and absolute motion.
            # Normalisation alone can make a quiet panel "win" from a small
            # head/hand movement, even while the real speaker has far more
            # mouth activity.  The raw-motion gates prevent those false jumps.
            if winner != current_zone:
                incumbent_score = norm[current_zone]
                raw_max = max(e[z] for z in available_zones)
                winner_abs = e[winner]
                current_abs = e[current_zone]
                candidate_visibility = visible_ratio(min(int(t * FPS), len(frame_files) - 1), winner, ONSET_FRAMES)
                current_visibility = visible_ratio(min(int(t * FPS), len(frame_files) - 1), current_zone, ONSET_FRAMES)
                strong_mouth_switch = (
                    winner_abs >= max(current_abs * STRONG_SWITCH_RAW, raw_max * STRONG_SWITCH_MIN_SHARE)
                    and norm[winner] >= max(norm[current_zone] * DOMINANCE_RATIO, 1.0)
                )
                if candidate_visibility < 0.35 and current_visibility >= 0.15 and not strong_mouth_switch:
                    winner = current_zone
                elif raw_max > 0 and winner_abs < raw_max * MIN_ABS_SHARE:
                    winner = current_zone
                elif current_abs > 0 and winner_abs / current_abs < ABSOLUTE_RATIO:
                    winner = current_zone
                elif incumbent_score > 0 and norm[winner] / incumbent_score < DOMINANCE_RATIO:
                    winner = current_zone
            current_zone = winner
            raw_states.append((t, winner, True))

        # ── Step 5: Onset-based transitions with minimum hold ─────────────────
        active_zone = raw_states[0][1]
        active_panel = raw_states[0][2]
        last_switch_t = 0.0
        transitions: list[tuple[float, int, bool]] = [(0.0, active_zone, active_panel)]

        for i in range(ONSET_FRAMES - 1, len(raw_states)):
            t, z, is_panel = raw_states[i]
            if is_panel != active_panel:
                transitions.append((t, z, is_panel))
                active_zone = z
                active_panel = is_panel
                last_switch_t = t
                continue

            if not is_panel:
                continue

            if z == active_zone:
                continue
            # Need ONSET_FRAMES consecutive frames in the new zone
            if not all(raw_states[i - j][1] == z and raw_states[i - j][2] for j in range(ONSET_FRAMES)):
                continue
            # Do not cut to a panel where the face is not visibly usable during
            # the onset. This catches "looking down but moving" false positives.
            if visible_ratio(i, z, ONSET_FRAMES) < 0.35:
                continue
            # Enforce minimum hold
            if t - last_switch_t < MIN_HOLD:
                continue
            # Transition detected — backdate to onset start
            onset_t = raw_states[i - ONSET_FRAMES + 1][0]
            transitions.append((onset_t, z, True))
            active_zone = z
            last_switch_t = t

        # ── Step 6: Build crop segments from transitions ──────────────────────
        segments: list[dict] = []
        for i, (t_start, z, is_panel) in enumerate(transitions):
            t_end = transitions[i + 1][0] if i + 1 < len(transitions) else duration
            if is_panel:
                crop = zone_to_crop(z)
                layout = "panel"
            else:
                start_idx = max(0, int(t_start * FPS))
                end_idx = min(len(frame_files) - 1, max(start_idx, int(t_end * FPS)))
                span = max(1, end_idx - start_idx)
                sample_closeup_indices = [
                    min(len(frame_files) - 1, start_idx + int(span * p))
                    for p in (0.25, 0.5, 0.75)
                ]
                crop = _safe_closeup_crop(
                    frame_files,
                    sample_closeup_indices,
                    face_cascade,
                    src_w,
                    src_h,
                    crop_w,
                    crop_h,
                )
                layout = "closeup"
            segments.append({
                "t_start": round(t_start, 1),
                "t_end":   round(t_end, 1),
                "layout": layout,
                **crop,
            })

        if not segments:
            return None

        segments[0]["t_start"] = 0.0
        segments[-1]["t_end"] = duration

        # Bridge short false-positive islands between two chunks of the same
        # speaker. A quiet panel can spike briefly from a head/hand movement;
        # if the crop immediately returns to the same journalist, keep the shot
        # stable instead of cutting away for a few seconds.
        SHORT_ISLAND = 5.0
        bridged: list[dict] = []
        i = 0
        while i < len(segments):
            if 0 < i < len(segments) - 1 and bridged:
                cur = segments[i]
                nxt = segments[i + 1]
                prev = bridged[-1]
                same_surrounding_crop = (
                    prev["x"] == nxt["x"]
                    and prev["y"] == nxt["y"]
                    and prev["w"] == nxt["w"]
                    and prev["h"] == nxt["h"]
                )
                if same_surrounding_crop and cur["t_end"] - cur["t_start"] <= SHORT_ISLAND:
                    prev["t_end"] = nxt["t_end"]
                    i += 2
                    continue
            bridged.append(dict(segments[i]))
            i += 1
        segments = bridged

        # Merge adjacent same-zone segments (safety net)
        merged = [dict(segments[0])]
        for seg in segments[1:]:
            if seg["x"] == merged[-1]["x"] and seg["y"] == merged[-1]["y"]:
                merged[-1]["t_end"] = seg["t_end"]
            else:
                merged.append(dict(seg))

        merged[-1]["t_end"] = duration

        # Print detected timeline for debug
        zone_names = ["izq", "ctr", "der"]
        print(f"    → {len(merged)} segmentos, crop_w={crop_w}px:")
        for s in merged:
            if s.get("layout") == "closeup":
                label = "primer-plano"
            else:
                zi = zone_centers.index(
                    min(zone_centers, key=lambda c: abs(c - (s['x'] + crop_w // 2)))
                )
                label = zone_names[zi]
            print(f"       {s['t_start']:.1f}s → {s['t_end']:.1f}s  {label} (x={s['x']})")

        return merged


def zoom_plan_path_for_output(output_path: Path) -> Path:
    return output_path.with_suffix(".zoom.json")


def _zoom_plan_matches(plan: dict, raw_clip: Path) -> bool:
    try:
        return (
            int(plan.get("version", 0)) == 1
            and int(plan.get("raw_mtime", -1)) == int(raw_clip.stat().st_mtime)
            and int(plan.get("raw_size", -1)) == int(raw_clip.stat().st_size)
            and isinstance(plan.get("segments"), list)
            and bool(plan["segments"])
        )
    except OSError:
        return False


def load_zoom_plan(plan_path: Path, raw_clip: Path) -> list[dict] | None:
    if not plan_path.exists():
        return None
    try:
        plan = json.loads(plan_path.read_text(encoding="utf-8"))
    except Exception:
        return None
    if not _zoom_plan_matches(plan, raw_clip):
        return None
    return normalize_zoom_segments(plan["segments"])


def save_zoom_plan(plan_path: Path, raw_clip: Path, segments: list[dict]) -> None:
    segments = normalize_zoom_segments(segments)
    plan_path.parent.mkdir(parents=True, exist_ok=True)
    payload = {
        "version": 1,
        "raw": raw_clip.name,
        "raw_mtime": int(raw_clip.stat().st_mtime),
        "raw_size": int(raw_clip.stat().st_size),
        "segments": segments,
    }
    plan_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def same_zoom_crop(a: dict, b: dict) -> bool:
    return all(a.get(key) == b.get(key) for key in ("x", "y", "w", "h"))


def normalize_zoom_segments(segments: list[dict]) -> list[dict]:
    """Remove tiny focus jumps before rendering dynamic speaker crops."""
    cleaned = [dict(seg) for seg in segments if float(seg.get("t_end", 0)) > float(seg.get("t_start", 0))]
    if not cleaned:
        return []

    cleaned.sort(key=lambda seg: float(seg["t_start"]))
    cleaned[0]["t_start"] = 0.0

    # Bridge short false-positive islands when the crop returns to the same
    # journalist immediately after the blip.
    bridged: list[dict] = []
    i = 0
    while i < len(cleaned):
        if 0 < i < len(cleaned) - 1 and bridged:
            cur = cleaned[i]
            nxt = cleaned[i + 1]
            prev = bridged[-1]
            cur_len = float(cur["t_end"]) - float(cur["t_start"])
            if same_zoom_crop(prev, nxt) and cur_len <= 1.25:
                prev["t_end"] = nxt["t_end"]
                i += 2
                continue
        bridged.append(dict(cleaned[i]))
        i += 1

    # Remove near-zero cuts even when they are not surrounded by the same crop.
    merged: list[dict] = []
    for seg in bridged:
        seg_len = float(seg["t_end"]) - float(seg["t_start"])
        if merged and same_zoom_crop(merged[-1], seg):
            merged[-1]["t_end"] = seg["t_end"]
            continue
        if merged and seg_len <= 0.75:
            merged[-1]["t_end"] = seg["t_end"]
            continue
        merged.append(dict(seg))

    if len(merged) > 1 and float(merged[-1]["t_end"]) - float(merged[-1]["t_start"]) <= 0.75:
        merged[-2]["t_end"] = merged[-1]["t_end"]
        merged.pop()

    for prev, nxt in zip(merged, merged[1:]):
        nxt["t_start"] = prev["t_end"]
    return merged


def encode_vertical_dynamic_zoom_from_segments(
    raw_clip: Path,
    ass_path: Path,
    output_path: Path,
    segments: list[dict],
) -> None:
    """Encode a vertical clip using a previously detected crop timeline."""
    segments = normalize_zoom_segments(segments)
    print(f"    → Reutilizando {len(segments)} plano(s) de encuadre guardados")
    with tempfile.TemporaryDirectory() as tmp:
        tmp_ass = Path(tmp) / "sub.ass"
        shutil.copy(ass_path, tmp_ass)
        esc = str(tmp_ass).replace("\\", "/").replace(":", r"\:")

        n = len(segments)

        # 1) Split input video into n copies
        split_out  = "".join(f"[v{i}]" for i in range(n))
        split_part = f"[0:v]split={n}{split_out}"

        # 2) Trim + crop + scale each copy
        seg_parts = []
        dims = probe_video_dimensions(raw_clip)
        if dims:
            segments = [sanitize_dynamic_crop(seg, dims[0], dims[1]) for seg in segments]

        for i, seg in enumerate(segments):
            t0 = f"{seg['t_start']:.3f}"
            t1 = f"{seg['t_end']:.3f}"
            x, y, w, h = seg["x"], seg["y"], seg["w"], seg["h"]
            seg_parts.append(
                f"[v{i}]trim={t0}:{t1},setpts=PTS-STARTPTS,"
                f"crop={w}:{h}:{x}:{y},"
                f"scale=1080:1920:force_original_aspect_ratio=increase:flags=lanczos,"
                f"crop=1080:1920,setsar=1[s{i}]"
            )

        # 3) Concat segments + normalise timestamps once + branding + burn subtitles
        fps_part = "[vc_raw]fps=fps=60000/1001[vc]"
        concat_in = "".join(f"[s{i}]" for i in range(n))
        concat_part = f"{concat_in}concat=n={n}:v=1:a=0[vc_raw]"
        logo_path = pyd_logo_path()
        video_label = "vc"
        post_parts: list[str] = []
        video_label = add_video_polish_filter(post_parts, video_label, "vc_polished")
        if logo_path:
            video_label = add_pyd_logo_filter(post_parts, video_label, 1, "branded", vertical=True)
        post_parts.append(f"[{video_label}]subtitles={esc}[vout]")
        audio_label = add_audio_polish_filter(post_parts, raw_clip)

        filter_complex = (
            split_part + ";"
            + ";".join(seg_parts) + ";"
            + concat_part + ";"
            + fps_part + ";"
            + ";".join(post_parts)
        )
        map_args = media_map_args(audio_label)

        run([
            FFMPEG_BIN, "-y",
            "-i", str(raw_clip),
            *(["-i", str(logo_path)] if logo_path else []),
            "-filter_complex", filter_complex,
            *map_args,
            "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF,
            "-c:a", "aac", "-b:a", AUDIO_BITRATE,
            "-movflags", "+faststart",
            str(output_path),
        ])


def encode_vertical_dynamic_zoom(
    raw_clip: Path,
    ass_path: Path,
    output_path: Path,
    *,
    reuse_zoom_plan: bool = False,
    zoom_plan_path: Path | None = None,
) -> None:
    """
    Produce 1080×1920 (9:16) clip with dynamic per-speaker zoom.

    Detects camera cuts + active speaker (mouth motion) to apply a different
    9:16 crop for each segment.  The audio stream is passed through unchanged.
    Falls back to static zoom → blurred background if detection yields nothing.

    ffmpeg strategy:
      split → N copies of the input video
      each copy: trim to segment timestamps, reset PTS, crop to speaker, scale to 1080×1920
      concat → single continuous video stream
      subtitles → burned on top
    """
    zoom_plan_path = zoom_plan_path or zoom_plan_path_for_output(output_path)
    if is_guest_interview_clip(raw_clip):
        try:
            zoom_plan_path.unlink()
        except FileNotFoundError:
            pass
        print("    → Layout con paneles chicos detectado; uso composición especial")
        encode_vertical_interview_layout(raw_clip, ass_path, output_path)
        return

    if reuse_zoom_plan:
        cached_segments = load_zoom_plan(zoom_plan_path, raw_clip)
        if cached_segments:
            try:
                encode_vertical_dynamic_zoom_from_segments(raw_clip, ass_path, output_path, cached_segments)
                return
            except (Exception, SystemExit) as exc:
                print(f"    → El plan de encuadre guardado falló ({exc}); recalculando encuadre…")
                try:
                    output_path.unlink()
                except FileNotFoundError:
                    pass

    print("    → Detectando planos y speakers dinámicos…")
    segments = detect_active_speaker_timeline(raw_clip)

    if not segments:
        print("    → Sin cambios de plano detectados → zoom estático")
        encode_vertical_zoom(raw_clip, ass_path, output_path)
        return

    print(f"    → {len(segments)} plano(s) con zoom dinámico:")
    for seg in segments:
        print(f"       {seg['t_start']:.1f}s–{seg['t_end']:.1f}s  "
              f"crop {seg['w']}×{seg['h']} @ ({seg['x']},{seg['y']})")

    save_zoom_plan(zoom_plan_path, raw_clip, segments)
    encode_vertical_dynamic_zoom_from_segments(raw_clip, ass_path, output_path, segments)


def encode_horizontal(raw_clip: Path, ass_path: Path, output_path: Path,
                       zoom: bool = False) -> None:
    """
    Produce 1920×1080 (16:9) clip — full frame, no speaker crop.

    For a multi-person panel the 16:9 source already frames the scene correctly.
    Any crop narrow enough to show one person destroys the 16:9 aspect or bleeds
    into the adjacent person.  The per-speaker zoom lives in the 9:16 version.
    The zoom parameter is accepted for API compatibility but intentionally unused.
    """
    with tempfile.TemporaryDirectory() as tmp:
        tmp_ass = Path(tmp) / "sub.ass"
        shutil.copy(ass_path, tmp_ass)
        esc = str(tmp_ass).replace("\\", "/").replace(":", r"\:")

        logo_path = pyd_logo_path()
        logo_input = ["-i", str(logo_path)] if logo_path else []
        parts = [
            "[0:v]scale=1920:1080:force_original_aspect_ratio=decrease:flags=lanczos,"
            "pad=1920:1080:(ow-iw)/2:(oh-ih)/2:black[base]"
        ]
        video_label = "base"
        video_label = add_video_polish_filter(parts, video_label, "polished")
        if logo_path:
            video_label = add_pyd_logo_filter(parts, video_label, 1, "branded", vertical=False)
        parts.append(f"[{video_label}]subtitles={esc}[vout]")
        audio_label = add_audio_polish_filter(parts, raw_clip)
        filter_complex = ";".join(parts)
        map_args = media_map_args(audio_label)
        run([
            FFMPEG_BIN, "-y",
            "-i", str(raw_clip),
            *logo_input,
            "-filter_complex", filter_complex,
            *map_args,
            "-c:v", "libx264", "-preset", VIDEO_PRESET, "-crf", VIDEO_CRF,
            "-c:a", "aac", "-b:a", AUDIO_BITRATE,
            "-movflags", "+faststart",
            str(output_path),
        ])


# ---------------------------------------------------------------------------
# Main orchestrator
# ---------------------------------------------------------------------------

def download_direct_video(video_url: str, output_dir: Path) -> Path:
    """Download a specific YouTube video by URL (supports watch?v=... and timestamps)."""
    print("\n[1/6] Downloading video…")

    # Extract clean video ID (strip timestamp params)
    match = re.search(r"(?:v=|youtu\.be/|/live/)([A-Za-z0-9_-]{11})", video_url)
    if not match:
        print("[ERROR] Could not extract video ID from URL", file=sys.stderr)
        sys.exit(1)
    video_id = match.group(1)
    clean_url = f"https://www.youtube.com/watch?v={video_id}"

    # Get title for logging
    result = run([*ytdlp_hq_cmd(), "--print", "%(title)s", clean_url], check=False)
    title = result.stdout.strip().split("\n")[0] if result.returncode == 0 else video_id
    print(f"  → Video: [{video_id}] {title}")

    video_path = output_dir / f"{video_id}.mp4"
    if video_path.exists():
        print(f"  → Already downloaded, skipping.")
        return video_path

    run([
        *ytdlp_hq_cmd(),
        "-f", YOUTUBE_HQ_FORMAT,
        "--merge-output-format", "mp4",
        "--concurrent-fragments", "8",
        "--retries", "infinite",
        "--fragment-retries", "infinite",
        "--retry-sleep", "fragment:exp=1:30",
        "--write-info-json",
        "-o", str(video_path),
        clean_url,
    ])
    return video_path


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Clipper automático de livestreams de Peñarol para redes sociales",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Ejemplos:
  # Video directo:
  python clip_workflow.py --video "https://www.youtube.com/watch?v=yhgEBROpRiA"

  # Último stream del canal:
  python clip_workflow.py --channel "https://www.youtube.com/@TuCanal"

  # Con opciones:
  python clip_workflow.py --video "https://www.youtube.com/watch?v=..." --clips 5 --whisper-model turbo
        """,
    )
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("--channel", help="URL del canal de YouTube (descarga el último stream)")
    group.add_argument("--video", help="URL directa del video de YouTube")

    parser.add_argument("--output-dir", default="./clips", help="Carpeta de salida (default: ./clips)")
    parser.add_argument("--clips", type=int, default=10, help="Cantidad de clips a generar (default: 10)")
    parser.add_argument(
        "--whisper-model",
        default="turbo",
        choices=["tiny", "base", "small", "medium", "large", "large-v1", "large-v2", "large-v3", "large-v3-turbo", "turbo"],
        help="Tamaño del modelo Whisper (default: turbo)",
    )
    parser.add_argument("--force", action="store_true", help="Ignorar caché y reprocesar todo")
    parser.add_argument("--zoom",  action="store_true",
                        help="Aplicar zoom automático al speaker (detección de caras con OpenCV)")
    parser.add_argument("--horizontal", action="store_true",
                        help="Generar también clips horizontales 16:9 (por defecto solo vertical)")
    args = parser.parse_args()

    # Note: ANTHROPIC_API_KEY is only needed for step 4 (moment selection).
    # If moments.json already exists in output_dir, the API call is skipped.

    # --- Directory structure ---
    output_dir = Path(args.output_dir).expanduser().resolve()
    raw_dir = output_dir / "raw"
    vertical_dir = output_dir / "vertical_9x16"     # TikTok / Instagram Reels
    horizontal_dir = output_dir / "horizontal_16x9"  # YouTube / reposts

    for d in [output_dir, raw_dir, vertical_dir, horizontal_dir]:
        d.mkdir(parents=True, exist_ok=True)

    # Clear cache if --force
    if args.force:
        for pattern in ["*.json", "*.wav"]:
            for f in output_dir.glob(pattern):
                f.unlink()
        print("  [force] Cache cleared.")

    # --- Pipeline ---
    if args.video:
        video_path = download_direct_video(args.video, output_dir)
    else:
        video_path = download_latest_video(args.channel, output_dir)
    audio_path = extract_audio(video_path, output_dir)
    transcript = transcribe_audio(audio_path, output_dir, args.whisper_model)
    moments = select_moments(transcript, args.clips, output_dir)

    print(f"\n[5-6/6] Cutting and encoding {len(moments)} clips…")
    segments = transcript.get("segments", [])

    for moment in sorted(moments, key=lambda m: m["rank"]):
        rank = moment["rank"]
        start = float(moment["start"])
        end = float(moment["end"])
        title = moment["title"]
        start = snap_start_to_segment(start, segments)

        # Safety clamp to the target social duration. snap_end_to_sentence may
        # extend a few seconds later only when it finds a cleaner ending.
        if end - start > TARGET_MAX_CLIP_DURATION:
            end = start + TARGET_MAX_CLIP_DURATION

        # Snap end to a complete phrase/pause near the selected range.
        end = snap_end_to_sentence(start, end, segments)
        end = min(end, start + ABSOLUTE_MAX_CLIP_DURATION)
        duration = end - start

        clip_name = f"{rank:02d}_{safe_name(title)}"
        print(f"\n  ── Clip #{rank}: {title} ({duration:.0f}s) ──")

        raw_path = raw_dir / f"{clip_name}.mp4"
        ass_v_path = raw_dir / f"{clip_name}_v.ass"
        ass_h_path = raw_dir / f"{clip_name}_h.ass"
        v_path = vertical_dir / f"{clip_name}_9x16.mp4"
        h_path = horizontal_dir / f"{clip_name}_16x9.mp4"

        raw_changed = not clip_cache_matches(raw_path, video_path, start, end)
        if raw_changed:
            cut_clip(video_path, start, end, raw_path)
            write_clip_cache_meta(raw_path, video_path, start, end)

        # Generate ASS subtitle files (style embedded, no force_style needed)
        ass_v_changed = generate_ass(segments, start, end, ass_v_path,
                                     play_res_x=1080, play_res_y=1920, font_size=82, margin_v=285)
        if args.horizontal:
            ass_h_changed = generate_ass(segments, start, end, ass_h_path,
                                         play_res_x=1920, play_res_y=1080, font_size=66, margin_v=100)
        else:
            ass_h_changed = False

        if not v_path.exists() or raw_changed or ass_v_changed:
            if args.zoom:
                encode_vertical_dynamic_zoom(raw_path, ass_v_path, v_path)
            else:
                encode_vertical(raw_path, ass_v_path, v_path)

        if args.horizontal and (not h_path.exists() or raw_changed or ass_h_changed):
            encode_horizontal(raw_path, ass_h_path, h_path, zoom=args.zoom)

    # --- Summary ---
    print("\n" + "=" * 65)
    print("  CLIPS LISTOS PARA PUBLICAR")
    print("=" * 65)
    print(f"\n  Carpeta base: {output_dir}")
    print(f"  raw/             → cortes crudos (sin subtítulos)")
    print(f"  vertical_9x16/   → TikTok / Instagram Reels (1080×1920)")
    print(f"  horizontal_16x9/ → YouTube (1920×1080)")
    print(f"\n  Momentos seleccionados:")
    for m in sorted(moments, key=lambda x: x["rank"]):
        dur = float(m["end"]) - float(m["start"])
        print(f"    #{m['rank']:2d} ({dur:.0f}s)  {m['title']}")
        print(f"         {m['reason']}")
    print(f"\n  ✅ {len(moments)} clips generados. ¡A publicar!")


if __name__ == "__main__":
    main()