import sys
import subprocess
import time
import threading
from pathlib import Path

LIMIT = int(sys.argv[1]) if len(sys.argv) > 1 else 10
SLEEP = 15  # 20 segundos

script = '/home/develop/edictos_py/central_edictos/procesamiento/homonimia/homonimia_lcdtm.py'

python = sys.executable

TIMEOUT_ITER = 300  # 5 minutos máximos por iteración

print(
    f'Iniciando loop infinito homonimia_lcdtm '
    f'limit={LIMIT} sleep={SLEEP}s',
    flush=True
)



i = 0

while True:
    i += 1

    print(f'--- Iteración {i} ---', flush=True)

    proc = subprocess.Popen(
        [python, '-u', str(script), str(LIMIT)],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True
    )

    def _leer():
        for line in proc.stdout:
            print(line, end='', flush=True)

    t = threading.Thread(target=_leer, daemon=True)
    t.start()

    t.join(timeout=TIMEOUT_ITER)

    if t.is_alive():
        print(
            f'TIMEOUT: iteración {i} superó '
            f'{TIMEOUT_ITER}s, matando proceso...',
            flush=True
        )

        proc.kill()
        proc.communicate()

    else:
        proc.wait()

    print(
        f'Iteración {i} finalizada. '
        f'Esperando {SLEEP // 60} minutos...',
        flush=True
    )

    time.sleep(SLEEP)