import os
import pytest
from typer.testing import CliRunner
from flowa.cli.main import app

runner = CliRunner()


# ── flowa init ────────────────────────────────────────────────────────────────

def test_init_cria_diretorio(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    result = runner.invoke(app, ["init"])
    assert result.exit_code == 0
    assert (tmp_path / "flowa_pipelines").is_dir()


def test_init_cria_etl_yaml(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    runner.invoke(app, ["init"])
    etl = tmp_path / "flowa_pipelines" / "etl.yaml"
    assert etl.exists()
    content = etl.read_text()
    assert "name: etl_pipeline" in content
    assert "extract" in content
    assert "transform" in content
    assert "load" in content


def test_init_idempotente(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    result1 = runner.invoke(app, ["init"])
    result2 = runner.invoke(app, ["init"])
    assert result1.exit_code == 0
    assert result2.exit_code == 0
    assert "already exists" in result2.output


def test_init_nao_sobrescreve_etl_existente(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    runner.invoke(app, ["init"])
    etl = tmp_path / "flowa_pipelines" / "etl.yaml"
    etl.write_text("# meu pipeline customizado")
    runner.invoke(app, ["init"])
    assert etl.read_text() == "# meu pipeline customizado"


# ── start_scheduler_background ───────────────────────────────────────────────

def test_scheduler_background_inicia_sem_pipelines(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    monkeypatch.setenv("FLOWA_DB_PATH", str(tmp_path / "test.db"))
    (tmp_path / "flowa_pipelines").mkdir()

    from flowa.scheduler.scheduler import start_scheduler_background
    bg = start_scheduler_background()
    assert bg.running
    bg.shutdown(wait=False)


def test_scheduler_background_registra_pipeline(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    monkeypatch.setenv("FLOWA_DB_PATH", str(tmp_path / "test.db"))
    pipelines_dir = tmp_path / "flowa_pipelines"
    pipelines_dir.mkdir()

    (pipelines_dir / "etl.yaml").write_text(
        "name: etl_pipeline\n"
        "schedule:\n"
        "  days: All Days\n"
        "  start: '09:00'\n"
        "  end: '10:00'\n"
        "  interval_minutes: 60\n"
        "steps:\n"
        "  - name: extract\n"
        "    run: echo extract\n"
    )

    from flowa.scheduler.scheduler import start_scheduler_background
    bg = start_scheduler_background()
    assert bg.running
    assert len(bg.get_jobs()) > 0
    bg.shutdown(wait=False)
