import asyncio
import fcntl
import json
import threading
import time
from pathlib import Path
from uuid import uuid4

import pytest
from fastapi.testclient import TestClient

from app.adapters import AdapterResult, PodmanAdapter
from app.config import Settings
from app.main import create_app
from app.schemas import CreateRun
from app.storage import ActiveRunConflict, IdempotencyConflict, Store


TOKEN = "test-service-token-that-is-long-enough-123456"
TABLE = "ventas_facturacion"


def settings_for(tmp_path: Path, **overrides) -> Settings:
    values = dict(
        token=TOKEN, database_path=tmp_path / "state.sqlite3", log_dir=tmp_path / "logs",
        host="127.0.0.1", port=8081, adapter="simulated", lock_path=tmp_path / ".full_sync.lock",
        max_request_bytes=16384, simulated_delay_seconds=0.005, podman_bin="/usr/bin/podman",
        podman_image="localhost/bi-sync:1.0", podman_network="superset_internal",
        podman_remote=False, sync_script="/opt/bi-sync/sync/sync_reporting.py", sync_directory="/opt/bi-sync/sync",
        podman_env_file="/opt/bi-sync/secrets/bi-sync.env", sync_timeout_seconds=10,
    )
    values.update(overrides)
    return Settings(**values)


def payload(run_id=None, tables=None):
    return {"run_id": str(run_id or uuid4()), "connection": "iberofarmacos", "mode": "full",
            "tables": tables or [TABLE]}


def headers(token=TOKEN):
    return {"Authorization": "Bearer " + token}


def wait_for_status(client, run_id, terminal="completed"):
    for _ in range(200):
        response = client.get("/api/v1/sync-runs/" + run_id, headers=headers())
        assert response.status_code == 200
        if response.json()["status"] in {terminal, "failed"}:
            return response.json()
        time.sleep(0.01)
    raise AssertionError("worker did not reach a terminal state")


def test_valid_submission_and_simulated_completion(tmp_path):
    app = create_app(settings_for(tmp_path))
    with TestClient(app) as client:
        request = payload()
        accepted = client.post("/api/v1/sync-runs", json=request, headers=headers())
        assert accepted.status_code == 202
        assert accepted.json() == {"run_id": request["run_id"], "status": "queued"}
        result = wait_for_status(client, request["run_id"])
        assert result["status"] == "completed"
        assert result["tables"][0]["status"] == "completed"
        assert result["tables"][0]["rows_imported"] == 0
        assert result["tables"][0]["started_at"].endswith("Z")


def test_second_worker_process_cannot_use_the_same_sqlite_database(tmp_path):
    settings = settings_for(tmp_path)
    with TestClient(create_app(settings)):
        with pytest.raises(RuntimeError, match="Only one worker process"):
            with TestClient(create_app(settings)):
                pass


@pytest.mark.parametrize("token", [None, "incorrect-token"])
def test_missing_or_incorrect_token_is_rejected(tmp_path, token):
    app = create_app(settings_for(tmp_path))
    with TestClient(app) as client:
        response = client.post("/api/v1/sync-runs", json=payload(), headers=headers(token) if token else {})
        assert response.status_code == 401


def test_same_uuid_same_request_is_idempotent_and_changed_request_conflicts(tmp_path):
    app = create_app(settings_for(tmp_path))
    with TestClient(app) as client:
        request = payload()
        first = client.post("/api/v1/sync-runs", json=request, headers=headers())
        duplicate = client.post("/api/v1/sync-runs", json=request, headers=headers())
        changed = dict(request, tables=["pedidos"])
        conflict = client.post("/api/v1/sync-runs", json=changed, headers=headers())
        assert first.status_code == 202
        assert duplicate.status_code == 200
        assert duplicate.json()["run_id"] == request["run_id"]
        assert conflict.status_code == 409


def test_two_simultaneous_requests_with_same_uuid_create_one_physical_run(tmp_path):
    app = create_app(settings_for(tmp_path, simulated_delay_seconds=0.1))
    request = payload()
    with TestClient(app) as client:
        barrier = threading.Barrier(3)
        responses = []

        def submit():
            barrier.wait()
            responses.append(client.post("/api/v1/sync-runs", json=request, headers=headers()))

        threads = [threading.Thread(target=submit) for _ in range(2)]
        for thread in threads:
            thread.start()
        barrier.wait()
        for thread in threads:
            thread.join()
        assert sorted(item.status_code for item in responses) == [200, 202]
        with Store(tmp_path / "state.sqlite3").connect() as conn:
            assert conn.execute("SELECT COUNT(*) FROM sync_runs WHERE run_id=?", (request["run_id"],)).fetchone()[0] == 1


@pytest.mark.parametrize("invalid", [
    {"connection": "other", "tables": [TABLE]},
    {"connection": "iberofarmacos", "tables": ["not_authorized"]},
])
def test_unknown_connection_and_table_are_rejected(tmp_path, invalid):
    app = create_app(settings_for(tmp_path))
    with TestClient(app) as client:
        response = client.post("/api/v1/sync-runs", json=payload(tables=invalid["tables"]) | {"connection": invalid["connection"]}, headers=headers())
        assert response.status_code == 422


class EventAdapter:
    def __init__(self, fail=False):
        self.fail = fail
        self.calls = []

    async def run_table(self, run_id, connection, table, log_path, on_event):
        self.calls.append((run_id, table))
        on_event({"event": "table_started", "name": table})
        on_event({"event": "table_progress", "name": table, "rows_imported": 3, "previous_rows": 2})
        if self.fail:
            on_event({"event": "table_failed", "name": table, "error_message": "safe test failure"})
            return AdapterResult(7, False)
        event = {"event": "table_completed", "name": table, "rows_imported": 5,
                 "previous_rows": 2, "backup_table": "backup_sales", "published": True}
        on_event(event)
        with log_path.open("a", encoding="utf-8") as log:
            log.write(json.dumps(event) + "\n")
        return AdapterResult(0, True)


def test_progress_is_visible_before_completion_and_worker_failure_is_terminal(tmp_path):
    adapter = EventAdapter()
    app = create_app(settings_for(tmp_path), adapter=adapter)
    with TestClient(app) as client:
        request = payload()
        client.post("/api/v1/sync-runs", json=request, headers=headers())
        result = wait_for_status(client, request["run_id"])
        assert result["tables"][0]["rows_imported"] == 5
        assert result["tables"][0]["previous_rows"] == 2
        assert result["tables"][0]["backup_table"] == "backup_sales"
        assert adapter.calls == [(request["run_id"], TABLE)]

    failed_adapter = EventAdapter(fail=True)
    failed_app = create_app(settings_for(tmp_path / "failed"), adapter=failed_adapter)
    with TestClient(failed_app) as client:
        request = payload()
        client.post("/api/v1/sync-runs", json=request, headers=headers())
        result = wait_for_status(client, request["run_id"], terminal="failed")
        assert result["status"] == "failed"
        assert result["tables"][0]["status"] == "failed"


def test_uncertain_sync_remains_running_and_blocks_a_second_run(tmp_path):
    class AmbiguousAdapter:
        async def run_table(self, run_id, connection, table, log_path, on_event):
            return AdapterResult(returncode=124, saw_publication=False, uncertain=True)

    app = create_app(settings_for(tmp_path), adapter=AmbiguousAdapter())
    with TestClient(app) as client:
        first = payload()
        client.post("/api/v1/sync-runs", json=first, headers=headers())
        for _ in range(100):
            current = client.get("/api/v1/sync-runs/" + first["run_id"], headers=headers()).json()
            if current["error_message"]:
                break
            time.sleep(0.01)
        assert current["status"] == "running"
        assert client.post("/api/v1/sync-runs", json=payload(), headers=headers()).status_code == 409


def test_missing_run_returns_404_and_invalid_authorization_is_checked_on_get(tmp_path):
    app = create_app(settings_for(tmp_path))
    with TestClient(app) as client:
        run_id = str(uuid4())
        assert client.get("/api/v1/sync-runs/" + run_id).status_code == 401
        assert client.get("/api/v1/sync-runs/" + run_id, headers=headers()).status_code == 404


def test_request_body_limit_applies_even_without_content_length(tmp_path):
    app = create_app(settings_for(tmp_path, max_request_bytes=32))
    with TestClient(app) as client:
        response = client.post("/api/v1/sync-runs", content=b"{" + b" " * 40 + b"}", headers=headers())
        assert response.status_code == 413


def test_restart_preserves_uncertain_running_state_and_blocks_new_run(tmp_path):
    settings = settings_for(tmp_path)
    store = Store(settings.database_path)
    store.initialize()
    run_id = str(uuid4())
    request = CreateRun.model_validate(payload(run_id))
    conn = store.connect()
    conn.execute("INSERT INTO sync_runs(run_id,request_hash,connection,mode,tables_json,status,created_at,started_at,log_reference) VALUES(?,?,?,?,?,'running','2026-01-01T00:00:00Z','2026-01-01T00:01:00Z',?)",
                 (run_id, Store.request_hash(request), "iberofarmacos", "full", json.dumps([TABLE]), run_id + ".jsonl"))
    conn.execute("INSERT INTO sync_run_tables(run_id,name,status,started_at) VALUES(?,?,'running','2026-01-01T00:01:00Z')", (run_id, TABLE))
    conn.close()
    app = create_app(settings)
    with TestClient(app) as client:
        current = client.get("/api/v1/sync-runs/" + run_id, headers=headers()).json()
        assert current["status"] == "running"
        assert "reconciliation" in current["error_message"].lower()
        assert client.post("/api/v1/sync-runs", json=payload(), headers=headers()).status_code == 409


def test_shutdown_mid_sync_keeps_run_uncertain_after_restart(tmp_path):
    started = threading.Event()

    class BlockingAdapter:
        async def run_table(self, run_id, connection, table, log_path, on_event):
            on_event({"event": "table_started", "name": table})
            started.set()
            await asyncio.Event().wait()

    settings = settings_for(tmp_path)
    app = create_app(settings, adapter=BlockingAdapter())
    request = payload()
    with TestClient(app) as client:
        client.post("/api/v1/sync-runs", json=request, headers=headers())
        assert started.wait(timeout=2)

    store = Store(settings.database_path)
    interrupted = store.snapshot(request["run_id"])
    assert interrupted["status"] == "running"
    assert interrupted["error_message"] is not None

    with TestClient(create_app(settings)) as client:
        current = client.get("/api/v1/sync-runs/" + request["run_id"], headers=headers()).json()
        assert current["status"] == "running"
        assert client.post("/api/v1/sync-runs", json=payload(), headers=headers()).status_code == 409


def test_reconciliation_requires_running_uncertain_state(tmp_path):
    store = Store(tmp_path / "state.sqlite3")
    store.initialize()
    assert not store.reconcile(str(uuid4()), "operator confirmed stop")
    run_id = str(uuid4())
    run = CreateRun.model_validate(payload(run_id))
    conn = store.connect()
    conn.execute("INSERT INTO sync_runs(run_id,request_hash,connection,mode,tables_json,status,created_at,started_at,log_reference,requires_reconciliation) VALUES(?,?,?,?,?,'running','2026-01-01T00:00:00Z','2026-01-01T00:01:00Z',?,1)",
                 (run_id, Store.request_hash(run), "iberofarmacos", "full", json.dumps([TABLE]), run_id + ".jsonl"))
    conn.close()
    assert store.reconcile(run_id, "operator confirmed stop")
    assert store.snapshot(run_id)["status"] == "failed"


def test_flock_prevents_worker_from_starting_until_existing_lock_is_released(tmp_path):
    settings = settings_for(tmp_path)
    settings.lock_path.parent.mkdir(parents=True, exist_ok=True)
    lock = settings.lock_path.open("a+")
    fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
    app = create_app(settings)
    try:
        with TestClient(app) as client:
            request = payload()
            client.post("/api/v1/sync-runs", json=request, headers=headers())
            time.sleep(0.08)
            assert client.get("/api/v1/sync-runs/" + request["run_id"], headers=headers()).json()["status"] == "queued"
            fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
            result = wait_for_status(client, request["run_id"])
            assert result["status"] == "completed"
    finally:
        lock.close()


def test_podman_command_is_fixed_and_subprocess_output_is_redacted(tmp_path, monkeypatch):
    settings = settings_for(tmp_path, adapter="podman")
    adapter = PodmanAdapter(settings)
    argv = adapter.argv(TABLE)
    assert argv[0:4] == ["/usr/bin/podman", "run", "--rm", "--network"]
    assert argv[-3:] == [settings.sync_script, "--view", TABLE]
    assert "shell=True" not in argv

    async def fake_create(*args, **kwargs):
        stream = asyncio.StreamReader()
        stream.feed_data((json.dumps({"event": "table_completed", "name": TABLE, "rows_imported": 5,
                                      "published": True, "error_message": "password=hunter2"}) + "\n").encode())
        stream.feed_eof()

        class Process:
            stdout = stream

            async def wait(self):
                return 0

            def terminate(self):
                pass

            def kill(self):
                pass

        return Process()

    monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_create)
    events = []
    result = asyncio.run(adapter.run_table(str(uuid4()), "iberofarmacos", TABLE, tmp_path / "log.jsonl", events.append))
    assert result.returncode == 0 and result.saw_publication
    assert events[0]["error_message"] == "password=[REDACTED]"
    assert "hunter2" not in (tmp_path / "log.jsonl").read_text()


def test_nonzero_subprocess_exit_never_reports_publication(tmp_path, monkeypatch):
    settings = settings_for(tmp_path)
    adapter = PodmanAdapter(settings)

    async def fake_create(*args, **kwargs):
        stream = asyncio.StreamReader()
        stream.feed_data(b"ordinary output\n")
        stream.feed_eof()

        class Process:
            stdout = stream

            async def wait(self):
                return 17

            def terminate(self): pass
            def kill(self): pass

        return Process()

    monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_create)
    result = asyncio.run(adapter.run_table(str(uuid4()), "iberofarmacos", TABLE, tmp_path / "log.jsonl", lambda event: None))
    assert result.returncode == 17
    assert not result.saw_publication
    assert result.uncertain


def test_database_constraints_reject_second_active_connection_and_changed_uuid(tmp_path):
    store = Store(tmp_path / "state.sqlite3")
    store.initialize()
    first = CreateRun.model_validate(payload())
    store.create(first)
    with pytest.raises(ActiveRunConflict):
        store.create(CreateRun.model_validate(payload()))
    with pytest.raises(IdempotencyConflict):
        store.create(CreateRun.model_validate(payload(first.run_id, ["pedidos"])))

