SHELL := /bin/bash
OS := $(shell uname -s)

# ======================
# Local (DEV) - python
# ======================
VENV ?= .venv
PY ?= $(VENV)/bin/python
BOOTSTRAP_PY ?=
SRC ?= app
PYTHONPATH_HOST ?= $(CURDIR)/src
PYTHONPATH_CONT ?= /app/src

AGENT_FILE ?= $(SRC).agent_entry
BRIDGE_MODULE ?= $(SRC).bridge_entry
RUN_DIR ?= .run
AGENT_PID_FILE ?= $(RUN_DIR)/agent.pid
BRIDGE_PID_FILE ?= $(RUN_DIR)/bridge.pid
AGENT_LOG_FILE ?= $(RUN_DIR)/agent.log
BRIDGE_LOG_FILE ?= $(RUN_DIR)/bridge.log

WS_HOST ?= 0.0.0.0
DEV_WS_PORT ?= 8000
AGENT_SERVER_PORT ?= 18081

# envs
ENV_DEV ?= .env.dev
ENV_PROD ?= .env.prod

# ======================
# Podman (PROD) - host network
# ======================
IMAGE ?= api-tia-lk:latest
POD_NAME ?= api-tia-pod

PROD_WS_PORT ?= 8000
EXPORT_DIR_HOST ?= /RemoteChannelsOutBound
EXPORT_DIR_CONT ?= /RemoteChannelsOutBound

# HuggingFace cache (turn-detector models)
HF_CACHE_VOL ?= lk-hf-cache
HF_HOME_CONT ?= /hf
HF_HUB_CACHE_CONT ?= /hf/hub

# ======================
# LiveKit (build/run) - host network
# ======================
LIVEKIT_IMAGE ?= livekit/livekit-server:latest
LIVEKIT_NAME ?= livekit-prod
LIVEKIT_CFG  ?= $(CURDIR)/livekit.yaml
LIVEKIT_PORT_HTTP ?= 7880
LIVEKIT_PORT_TCP ?= 7881

.PHONY: help \
  setup check-venv \
  agent agent-models bridge test \
  agent-up agent-down agent-status agent-logs \
  bridge-up bridge-down bridge-status bridge-logs \
  local-up local-down local-status local-logs local-stresstest \
  docker-build docker-models docker-up docker-down docker-status docker-logs docker-logs-bridge \
  livekit livekit-stop livekit-logs livekit-status livekit-config-check \
  copy-logs download-call-segments download-entire-calls

help:
	@echo "Targets (DEV local):"
	@echo "  make setup           - cria $(VENV), instala dependencias e prepara $(ENV_DEV)"
	@echo "  make local-up        - sobe livekit + bridge + agent em background"
	@echo "  make local-down      - derruba bridge + agent locais e para o livekit"
	@echo "  make local-status    - mostra status do livekit + pids locais"
	@echo "  make local-logs      - informa onde estao os logs locais"
	@echo "  make local-stresstest - valida STT/TTS/Bridge/LiveKit reais e gera report.md"
	@echo "  make agent           - roda agent (usa $(ENV_DEV))"
	@echo "  make agent-up        - sobe agent em background"
	@echo "  make agent-down      - derruba agent local em background"
	@echo "  make agent-logs      - tail do log local do agent"
	@echo "  make agent-models    - baixa modelos locais do turn-detector (usa $(ENV_DEV))"
	@echo "  make bridge          - roda bridge (usa $(ENV_DEV)) na porta $(DEV_WS_PORT)"
	@echo "  make bridge-up       - sobe bridge em background"
	@echo "  make bridge-down     - derruba bridge local em background"
	@echo "  make bridge-logs     - tail do log local do bridge"
	@echo "  make download-call-segments DATE=AAAA-MM-DD SESSION_ID=id [BUCKET=nome]"
	@echo "  make download-entire-calls DATE=AAAA-MM-DD [BUCKET=nome]"
	@echo "  make test            - roda a suite pytest com PYTHONPATH=src"
	@echo
	@echo "Targets (PROD podman / host network):"
	@echo "  make docker-build    - build imagem (usa PROD por padrão)"
	@echo "  make docker-models   - baixa modelos do turn-detector no volume $(HF_CACHE_VOL)"
	@echo "  make docker-up       - sobe agent+bridge no pod (host network), bridge na porta $(PROD_WS_PORT)"
	@echo "  make docker-logs     - logs do agent"
	@echo "  make docker-logs-bridge - logs do bridge"
	@echo "  make docker-down     - derruba pod"
	@echo
	@echo "Targets (LiveKit host network):"
	@echo "  make livekit         - sobe LiveKit (host network)"
	@echo "  make livekit-logs    - logs LiveKit"
	@echo "  make livekit-stop    - remove container LiveKit"

# ======================
# DEV (local)
# ======================
setup:
	@if [ -x "$(PY)" ]; then \
		if $(PY) -c 'import sys; raise SystemExit(0 if (sys.version_info.major == 3 and 9 <= sys.version_info.minor <= 13) else 1)' >/dev/null 2>&1; then \
			echo "[make] usando virtualenv existente em $(VENV)"; \
		else \
			echo "ERRO: $(VENV) usa uma versao de Python nao suportada por este projeto."; \
			echo "Remova $(VENV) e rode 'make BOOTSTRAP_PY=python3.12 setup'."; \
			exit 1; \
		fi; \
	else \
		bootstrap_py="$(BOOTSTRAP_PY)"; \
		if [ -n "$$bootstrap_py" ]; then \
			if ! command -v "$$bootstrap_py" >/dev/null 2>&1; then \
				echo "ERRO: interpretador '$$bootstrap_py' nao encontrado no PATH."; \
				exit 1; \
			fi; \
			if ! "$$bootstrap_py" -c 'import sys; raise SystemExit(0 if (sys.version_info.major == 3 and 9 <= sys.version_info.minor <= 13) else 1)' >/dev/null 2>&1; then \
				echo "ERRO: '$$bootstrap_py' nao eh compativel. Use Python 3.9-3.13."; \
				exit 1; \
			fi; \
		else \
			for candidate in python3.13 python3.12 python3.11 python3.10 python3.9 python3 python; do \
				if command -v "$$candidate" >/dev/null 2>&1 && "$$candidate" -c 'import sys; raise SystemExit(0 if (sys.version_info.major == 3 and 9 <= sys.version_info.minor <= 13) else 1)' >/dev/null 2>&1; then \
					bootstrap_py="$$candidate"; \
					break; \
				fi; \
			done; \
		fi; \
		if [ -n "$$bootstrap_py" ]; then \
			echo "[make] criando virtualenv com $$bootstrap_py"; \
			"$$bootstrap_py" -m venv "$(VENV)"; \
		elif command -v uv >/dev/null 2>&1; then \
			echo "ERRO: nenhum Python compativel encontrado no PATH."; \
			echo "Instale Python 3.9-3.13 ou rode 'make BOOTSTRAP_PY=python3.12 setup'."; \
			exit 1; \
		else \
			echo "ERRO: nenhum interpretador encontrado. Instale Python 3.9-3.13 e rode 'make setup' novamente."; \
			exit 1; \
		fi; \
	fi
	@$(PY) -m pip install --upgrade pip
	@$(PY) -m pip install -r requirements.txt
	@if [ ! -f "$(ENV_DEV)" ]; then \
		cp .env.example "$(ENV_DEV)"; \
		echo "[make] criado $(ENV_DEV) a partir de .env.example"; \
	fi
	@echo "[make] ambiente pronto. Para rodar os testes: make test"

check-venv:
	@if [ ! -x "$(PY)" ]; then \
		echo "ERRO: virtualenv nao encontrado em $(PY). Rode 'make setup' antes."; \
		exit 1; \
	fi
	@if ! $(PY) -c 'import sys; raise SystemExit(0 if (sys.version_info.major == 3 and 9 <= sys.version_info.minor <= 13) else 1)' >/dev/null 2>&1; then \
		echo "ERRO: o virtualenv em $(VENV) nao usa um Python suportado."; \
		echo "Remova $(VENV) e rode 'make BOOTSTRAP_PY=python3.12 setup'."; \
		exit 1; \
	fi

agent: check-venv
	@set -a; [ -f "$(ENV_DEV)" ] && source "$(ENV_DEV)"; set +a; \
	AGENT_SERVER_PORT="$(AGENT_SERVER_PORT)" \
	STT_DUMP_DIR="$${AGENT_DIAG_STT_DUMP_DIR:-$${STT_DUMP_DIR:-}}" \
	FLOW_LOG_VAD_DECISIONS="$${AGENT_DIAG_FLOW_LOG_VAD_DECISIONS:-$${FLOW_LOG_VAD_DECISIONS:-0}}" \
	FLOW_LOG_VAD_ACTIVITY="$${AGENT_DIAG_FLOW_LOG_VAD_ACTIVITY:-$${FLOW_LOG_VAD_ACTIVITY:-0}}" \
	FLOW_LOG_VAD_ACTIVITY_MIN_PROB="$${AGENT_DIAG_FLOW_LOG_VAD_ACTIVITY_MIN_PROB:-$${FLOW_LOG_VAD_ACTIVITY_MIN_PROB:-0.03}}" \
	PYTHONPATH="$(PYTHONPATH_HOST):$$PYTHONPATH" \
	$(PY) -m $(AGENT_FILE) start --log-level info

agent-models: check-venv
	@set -a; [ -f "$(ENV_DEV)" ] && source "$(ENV_DEV)"; set +a; \
	AGENT_SERVER_PORT="$(AGENT_SERVER_PORT)" PYTHONPATH="$(PYTHONPATH_HOST):$$PYTHONPATH" $(PY) -m $(AGENT_FILE) download-files

bridge: check-venv
	@set -a; [ -f "$(ENV_DEV)" ] && source "$(ENV_DEV)"; set +a; \
	PYTHONPATH="$(PYTHONPATH_HOST):$$PYTHONPATH" $(PY) -m $(BRIDGE_MODULE) --host $(WS_HOST) --port $(DEV_WS_PORT) --log-level info

download-call-segments: check-venv
	@test -n "$(DATE)" || (echo "ERRO: informe DATE=AAAA-MM-DD"; exit 2)
	@test -n "$(SESSION_ID)" || (echo "ERRO: informe SESSION_ID=<id-da-chamada>"; exit 2)
	@set -a; [ -f "$(ENV_DEV)" ] && source "$(ENV_DEV)"; set +a; \
	PYTHONPATH="$(PYTHONPATH_HOST):$$PYTHONPATH" \
	$(PY) -m app.tools.oci_audio_download \
	$(if $(BUCKET),--bucket "$(BUCKET)",) \
	segments --date "$(DATE)" --session-id "$(SESSION_ID)"

download-entire-calls: check-venv
	@test -n "$(DATE)" || (echo "ERRO: informe DATE=AAAA-MM-DD"; exit 2)
	@set -a; [ -f "$(ENV_DEV)" ] && source "$(ENV_DEV)"; set +a; \
	PYTHONPATH="$(PYTHONPATH_HOST):$$PYTHONPATH" \
	$(PY) -m app.tools.oci_audio_download \
	$(if $(BUCKET),--bucket "$(BUCKET)",) \
	entire-calls --date "$(DATE)"

test: check-venv
	PYTHONPATH="$(PYTHONPATH_HOST):$$PYTHONPATH" $(PY) -m pytest

agent-up: check-venv
	@mkdir -p "$(RUN_DIR)"
	@if [ -f "$(AGENT_PID_FILE)" ] && kill -0 "$$(cat "$(AGENT_PID_FILE)")" >/dev/null 2>&1; then \
		echo "[make] agent ja esta rodando com pid $$(cat "$(AGENT_PID_FILE)")"; \
		exit 0; \
	fi
	@port_pids="$$(lsof -t -iTCP:$(AGENT_SERVER_PORT) -sTCP:LISTEN 2>/dev/null || true)"; \
	if [ -n "$$port_pids" ]; then \
		echo "ERRO: a porta $(AGENT_SERVER_PORT) ja esta em uso pelos pid(s): $$port_pids"; \
		echo "Rode 'make agent-down' para limpar o worker local antigo ou finalize o processo manualmente."; \
		exit 1; \
	fi
	@nohup /bin/bash -lc 'set -a; [ -f "$(ENV_DEV)" ] && source "$(ENV_DEV)"; set +a; AGENT_SERVER_PORT="$(AGENT_SERVER_PORT)" STT_DUMP_DIR="$${AGENT_DIAG_STT_DUMP_DIR:-$${STT_DUMP_DIR:-}}" FLOW_LOG_VAD_DECISIONS="$${AGENT_DIAG_FLOW_LOG_VAD_DECISIONS:-$${FLOW_LOG_VAD_DECISIONS:-0}}" FLOW_LOG_VAD_ACTIVITY="$${AGENT_DIAG_FLOW_LOG_VAD_ACTIVITY:-$${FLOW_LOG_VAD_ACTIVITY:-0}}" FLOW_LOG_VAD_ACTIVITY_MIN_PROB="$${AGENT_DIAG_FLOW_LOG_VAD_ACTIVITY_MIN_PROB:-$${FLOW_LOG_VAD_ACTIVITY_MIN_PROB:-0.03}}" PYTHONPATH="$(PYTHONPATH_HOST):$$PYTHONPATH" exec "$(PY)" -m $(AGENT_FILE) start --log-level info' >"$(AGENT_LOG_FILE)" 2>&1 & echo $$! >"$(AGENT_PID_FILE)"
	@sleep 1
	@if kill -0 "$$(cat "$(AGENT_PID_FILE)")" >/dev/null 2>&1; then \
		echo "[make] agent iniciado em background (pid $$(cat "$(AGENT_PID_FILE)"))"; \
		echo "[make] log: $(AGENT_LOG_FILE)"; \
	else \
		echo "ERRO: agent falhou ao iniciar. Veja $(AGENT_LOG_FILE)"; \
		rm -f "$(AGENT_PID_FILE)"; \
		exit 1; \
	fi

agent-down:
	@if [ -f "$(AGENT_PID_FILE)" ]; then \
		pid="$$(cat "$(AGENT_PID_FILE)")"; \
		if kill -0 "$$pid" >/dev/null 2>&1; then \
			kill "$$pid" >/dev/null 2>&1 || true; \
			sleep 1; \
			if kill -0 "$$pid" >/dev/null 2>&1; then \
				kill -9 "$$pid" >/dev/null 2>&1 || true; \
				echo "[make] agent encerrado com SIGKILL (pid $$pid)"; \
			else \
				echo "[make] agent encerrado (pid $$pid)"; \
			fi; \
		else \
			echo "[make] agent nao estava rodando, removendo pid stale"; \
		fi; \
		rm -f "$(AGENT_PID_FILE)"; \
	else \
		echo "[make] agent nao esta rodando"; \
	fi
	@port_pids="$$(lsof -t -iTCP:$(AGENT_SERVER_PORT) -sTCP:LISTEN 2>/dev/null || true)"; \
	if [ -n "$$port_pids" ]; then \
		for pid in $$port_pids; do \
			kill "$$pid" >/dev/null 2>&1 || true; \
			sleep 1; \
			if kill -0 "$$pid" >/dev/null 2>&1; then \
				kill -9 "$$pid" >/dev/null 2>&1 || true; \
				echo "[make] worker do agent encerrado com SIGKILL na porta $(AGENT_SERVER_PORT) (pid $$pid)"; \
			else \
				echo "[make] worker do agent encerrado na porta $(AGENT_SERVER_PORT) (pid $$pid)"; \
			fi; \
		done; \
	fi

agent-status:
	@if [ -f "$(AGENT_PID_FILE)" ] && kill -0 "$$(cat "$(AGENT_PID_FILE)")" >/dev/null 2>&1; then \
		echo "agent: running (pid $$(cat "$(AGENT_PID_FILE)"))"; \
	elif [ -n "$$(lsof -t -iTCP:$(AGENT_SERVER_PORT) -sTCP:LISTEN 2>/dev/null || true)" ]; then \
		echo "agent: running (listener na porta $(AGENT_SERVER_PORT) sem pid file)"; \
	else \
		echo "agent: stopped"; \
	fi

agent-logs:
	@if [ ! -f "$(AGENT_LOG_FILE)" ]; then \
		echo "ERRO: log do agent nao encontrado em $(AGENT_LOG_FILE)"; \
		exit 1; \
	fi
	@tail -f "$(AGENT_LOG_FILE)"

bridge-up: check-venv
	@mkdir -p "$(RUN_DIR)"
	@if [ -f "$(BRIDGE_PID_FILE)" ] && kill -0 "$$(cat "$(BRIDGE_PID_FILE)")" >/dev/null 2>&1; then \
		echo "[make] bridge ja esta rodando com pid $$(cat "$(BRIDGE_PID_FILE)")"; \
		exit 0; \
	fi
	@port_pids="$$(lsof -t -iTCP:$(DEV_WS_PORT) -sTCP:LISTEN 2>/dev/null || true)"; \
	if [ -n "$$port_pids" ]; then \
		echo "ERRO: a porta $(DEV_WS_PORT) ja esta em uso pelos pid(s): $$port_pids"; \
		echo "Rode 'make bridge-down' para limpar o bridge local antigo ou finalize o processo manualmente."; \
		exit 1; \
	fi
	@nohup /bin/bash -lc 'set -a; [ -f "$(ENV_DEV)" ] && source "$(ENV_DEV)"; set +a; PYTHONPATH="$(PYTHONPATH_HOST):$$PYTHONPATH" exec "$(PY)" -m $(BRIDGE_MODULE) --host "$(WS_HOST)" --port "$(DEV_WS_PORT)" --log-level info' >"$(BRIDGE_LOG_FILE)" 2>&1 & echo $$! >"$(BRIDGE_PID_FILE)"
	@sleep 1
	@if kill -0 "$$(cat "$(BRIDGE_PID_FILE)")" >/dev/null 2>&1; then \
		echo "[make] bridge iniciado em background (pid $$(cat "$(BRIDGE_PID_FILE)"))"; \
		echo "[make] log: $(BRIDGE_LOG_FILE)"; \
	else \
		echo "ERRO: bridge falhou ao iniciar. Veja $(BRIDGE_LOG_FILE)"; \
		rm -f "$(BRIDGE_PID_FILE)"; \
		exit 1; \
	fi

bridge-down:
	@if [ -f "$(BRIDGE_PID_FILE)" ]; then \
		pid="$$(cat "$(BRIDGE_PID_FILE)")"; \
		if kill -0 "$$pid" >/dev/null 2>&1; then \
			kill "$$pid" >/dev/null 2>&1 || true; \
			sleep 1; \
			if kill -0 "$$pid" >/dev/null 2>&1; then \
				kill -9 "$$pid" >/dev/null 2>&1 || true; \
				echo "[make] bridge encerrado com SIGKILL (pid $$pid)"; \
			else \
				echo "[make] bridge encerrado (pid $$pid)"; \
			fi; \
		else \
			echo "[make] bridge nao estava rodando, removendo pid stale"; \
		fi; \
		rm -f "$(BRIDGE_PID_FILE)"; \
	else \
		echo "[make] bridge nao esta rodando"; \
	fi
	@port_pids="$$(lsof -t -iTCP:$(DEV_WS_PORT) -sTCP:LISTEN 2>/dev/null || true)"; \
	if [ -n "$$port_pids" ]; then \
		for pid in $$port_pids; do \
			kill "$$pid" >/dev/null 2>&1 || true; \
			sleep 1; \
			if kill -0 "$$pid" >/dev/null 2>&1; then \
				kill -9 "$$pid" >/dev/null 2>&1 || true; \
				echo "[make] worker do bridge encerrado com SIGKILL na porta $(DEV_WS_PORT) (pid $$pid)"; \
			else \
				echo "[make] worker do bridge encerrado na porta $(DEV_WS_PORT) (pid $$pid)"; \
			fi; \
		done; \
	fi

bridge-status:
	@if [ -f "$(BRIDGE_PID_FILE)" ] && kill -0 "$$(cat "$(BRIDGE_PID_FILE)")" >/dev/null 2>&1; then \
		echo "bridge: running (pid $$(cat "$(BRIDGE_PID_FILE)"))"; \
	elif [ -n "$$(lsof -t -iTCP:$(DEV_WS_PORT) -sTCP:LISTEN 2>/dev/null || true)" ]; then \
		echo "bridge: running (listener na porta $(DEV_WS_PORT) sem pid file)"; \
	else \
		echo "bridge: stopped"; \
	fi

bridge-logs:
	@if [ ! -f "$(BRIDGE_LOG_FILE)" ]; then \
		echo "ERRO: log do bridge nao encontrado em $(BRIDGE_LOG_FILE)"; \
		exit 1; \
	fi
	@tail -f "$(BRIDGE_LOG_FILE)"

local-up: livekit bridge-up agent-up
	@echo "[make] ambiente local iniciado"
	@echo "[make] bridge: http://127.0.0.1:$(DEV_WS_PORT)/voice-client"
	@echo "[make] livekit: ws://127.0.0.1:$(LIVEKIT_PORT_HTTP)"
	@echo "[make] logs: $(RUN_DIR)"

local-down:
	@$(MAKE) --no-print-directory agent-down
	@$(MAKE) --no-print-directory bridge-down
	@$(MAKE) --no-print-directory livekit-stop

local-status:
	@$(MAKE) --no-print-directory bridge-status
	@$(MAKE) --no-print-directory agent-status
	@$(MAKE) --no-print-directory livekit-status

local-logs:
	@echo "bridge log: $(BRIDGE_LOG_FILE)"
	@echo "agent log: $(AGENT_LOG_FILE)"

local-stresstest: check-venv
	@diag_dump_dir="$${STT_DUMP_DIR:-$${STRESS_REPORT_DIR:-$(RUN_DIR)/local-stresstest}/stt_dumps}"; \
	mkdir -p "$$diag_dump_dir"; \
	if [ "$${STRESS_RESTART_AGENT_FOR_DIAGNOSTICS:-1}" = "1" ]; then \
		$(MAKE) --no-print-directory agent-down; \
	fi; \
	AGENT_DIAG_STT_DUMP_DIR="$$diag_dump_dir" \
	AGENT_DIAG_FLOW_LOG_VAD_DECISIONS="$${FLOW_LOG_VAD_DECISIONS:-1}" \
	AGENT_DIAG_FLOW_LOG_VAD_ACTIVITY="$${FLOW_LOG_VAD_ACTIVITY:-1}" \
	AGENT_DIAG_FLOW_LOG_VAD_ACTIVITY_MIN_PROB="$${FLOW_LOG_VAD_ACTIVITY_MIN_PROB:-0.03}" \
	$(MAKE) --no-print-directory local-up
	@set -a; [ -f "$(ENV_DEV)" ] && source "$(ENV_DEV)"; set +a; \
	STT_DUMP_DIR="$${STT_DUMP_DIR:-$${STRESS_REPORT_DIR:-$(RUN_DIR)/local-stresstest}/stt_dumps}" \
	FLOW_LOG_VAD_DECISIONS="$${FLOW_LOG_VAD_DECISIONS:-1}" \
	FLOW_LOG_VAD_ACTIVITY="$${FLOW_LOG_VAD_ACTIVITY:-1}" \
	FLOW_LOG_VAD_ACTIVITY_MIN_PROB="$${FLOW_LOG_VAD_ACTIVITY_MIN_PROB:-0.03}" \
	STRESS_ENV_FILE="$(ENV_DEV)" \
	STRESS_BRIDGE_URL="$${STRESS_BRIDGE_URL:-ws://127.0.0.1:$(DEV_WS_PORT)/ws/agent}" \
	STRESS_BRIDGE_HEALTH_URL="$${STRESS_BRIDGE_HEALTH_URL:-http://127.0.0.1:$(DEV_WS_PORT)/health}" \
	STRESS_AGENT_HEALTH_URL="$${STRESS_AGENT_HEALTH_URL:-http://127.0.0.1:$(AGENT_SERVER_PORT)/}" \
	PYTHONPATH="$(PYTHONPATH_HOST):$$PYTHONPATH" \
	$(PY) -m app.tools.local_stresstest

# ======================
# PROD (podman): build + models + up
# ======================
docker-build:
	# build sempre mirando PROD (env file usado no run) e bridge exposto em 8000
	podman build --no-cache -t $(IMAGE) .

docker-models: docker-build
	@podman volume create $(HF_CACHE_VOL) >/dev/null 2>&1 || true
	@echo "[make] downloading turn-detector models into volume $(HF_CACHE_VOL)..."
	podman run --rm --network host \
		--env-file $(ENV_PROD) \
		-v $(HF_CACHE_VOL):$(HF_HOME_CONT):Z \
		-e HF_HOME=$(HF_HOME_CONT) \
		-e HF_HUB_CACHE=$(HF_HUB_CACHE_CONT) \
		-e PYTHONPATH=$(PYTHONPATH_CONT) \
		$(IMAGE) \
		python -m $(AGENT_FILE) download-files

docker-up: docker-build docker-models
	@podman pod rm -f $(POD_NAME) >/dev/null 2>&1 || true
	podman pod create --name $(POD_NAME) --network host

	# AGENT (PROD) - host network
	podman run -d --replace --name $(POD_NAME)-agent --pod $(POD_NAME) \
		--env-file $(ENV_PROD) \
		-v $(EXPORT_DIR_HOST):$(EXPORT_DIR_CONT):Z \
		-v $(HF_CACHE_VOL):$(HF_HOME_CONT):Z \
		-e EXPORT_DIR=$(EXPORT_DIR_CONT) \
		-e HF_HOME=$(HF_HOME_CONT) \
		-e HF_HUB_CACHE=$(HF_HUB_CACHE_CONT) \
		-e LIVEKIT_URL=ws://127.0.0.1:$(LIVEKIT_PORT_HTTP) \
		-e PYTHONPATH=$(PYTHONPATH_CONT) \
		$(IMAGE) \
		python -m $(AGENT_FILE) start --log-level info

	# BRIDGE (PROD) - expõe na porta 8000 (host)
	podman run -d --replace --name $(POD_NAME)-bridge --pod $(POD_NAME) \
		--env-file $(ENV_PROD) \
		-v $(HF_CACHE_VOL):$(HF_HOME_CONT):Z \
		-e HF_HOME=$(HF_HOME_CONT) \
		-e HF_HUB_CACHE=$(HF_HUB_CACHE_CONT) \
		-e WS_HOST=0.0.0.0 \
		-e WS_PORT=$(PROD_WS_PORT) \
		-e PYTHONPATH=$(PYTHONPATH_CONT) \
		$(IMAGE) \
		python -m $(BRIDGE_MODULE) --host 0.0.0.0 --port $(PROD_WS_PORT) --log-level info

docker-down:
	@podman pod rm -f $(POD_NAME) >/dev/null 2>&1 || true

docker-status:
	@podman pod ps --filter "name=$(POD_NAME)" || true
	@podman ps --filter "name=$(POD_NAME)-" || true

docker-logs:
	@podman logs -f $(POD_NAME)-agent

docker-logs-bridge:
	@podman logs -f $(POD_NAME)-bridge

# ======================
# LiveKit (host network)
# ======================
livekit-stop:
	@podman rm -f $(LIVEKIT_NAME) >/dev/null 2>&1 || true

livekit-config-check:
	@test -f "$(LIVEKIT_CFG)" || (echo "ERRO: arquivo $(LIVEKIT_CFG) nao existe"; exit 1)

livekit: livekit-stop livekit-config-check
ifeq ($(OS),Darwin)
	podman run -d --name $(LIVEKIT_NAME) \
		-p $(LIVEKIT_PORT_HTTP):7880 \
		-p $(LIVEKIT_PORT_TCP):7881 \
		-v "$(LIVEKIT_CFG):/etc/livekit.yaml:ro" \
		$(LIVEKIT_IMAGE) \
		--config /etc/livekit.yaml
	@echo "LiveKit subiu (macOS/Podman: portas publicadas)."
	@echo "Signal URL: ws://127.0.0.1:$(LIVEKIT_PORT_HTTP)"
	@echo "RTC TCP URL: 127.0.0.1:$(LIVEKIT_PORT_TCP)"
else
	podman run -d --name $(LIVEKIT_NAME) \
		--network host \
		-v "$(LIVEKIT_CFG):/etc/livekit.yaml:ro" \
		$(LIVEKIT_IMAGE) \
		--config /etc/livekit.yaml
	@echo "LiveKit subiu (host network)."
	@echo "Signal URL: ws://127.0.0.1:$(LIVEKIT_PORT_HTTP)"
endif

livekit-logs:
	podman logs -f $(LIVEKIT_NAME)

livekit-status:
	@podman ps --filter "name=$(LIVEKIT_NAME)"

CONTAINER=api-tia-pod-agent
SHELL_IN=sh

BACKUP_DIR=backup_logs
DATE=$(shell date +%Y%m%d_%H%M%S)

copy-logs:
	@DEST="backup_logs_$$(date +%Y%m%d_%H%M%S)" && \
	mkdir -p "$$DEST" && \
	podman cp api-tia-pod-agent:/app/logs "$$DEST/logs" || true && \
	podman cp api-tia-pod-agent:/app/timeline "$$DEST/timeline" || true && \
	podman cp api-tia-pod-agent:/app/log_agent "$$DEST/log_agent" || true && \
	echo "Copiado para $$DEST"

