# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations

from collections.abc import Sequence
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING

import pytest
from fastapi import HTTPException
from sqlalchemy import delete, select

from airflow import __version__ as airflow_version
from airflow.providers.common.compat.sdk import timezone
from airflow.providers.edge3 import __version__ as edge_provider_version
from airflow.providers.edge3.cli.worker import EdgeWorker
from airflow.providers.edge3.models.edge_worker import (
    EdgeWorkerModel,
    EdgeWorkerState,
    set_worker_concurrency,
)
from airflow.providers.edge3.worker_api.datamodels import WorkerQueueUpdateBody, WorkerStateBody
from airflow.providers.edge3.worker_api.routes.worker import (
    _assert_version,
    _version,
    register,
    set_state,
    update_queues,
)

from tests_common.test_utils.config import conf_vars

if TYPE_CHECKING:
    from sqlalchemy.orm import Session

pytestmark = pytest.mark.db_test


class TestWorkerApiRoutes:
    MOCK_SYSINFO: dict[str, str | int | float | datetime] = {
        "status": 20,
        "airflow_version": airflow_version,
        "edge_provider_version": edge_provider_version,
        "python_version": "3.10.17 (main, Apr  9 2025, 04:03:39) [Clang 20.1.0 ]",
        "worker_start_time": "2026-04-18T21:10:42.714344",
        "concurrency": 8,
        "free_concurrency": 8,
    }

    @pytest.fixture
    def cli_worker(self, tmp_path: Path) -> EdgeWorker:
        test_worker = EdgeWorker(str(tmp_path / "mock.pid"), "mock", None, 8)
        return test_worker

    @pytest.fixture(autouse=True)
    def setup_test_cases(self, session: Session):
        session.execute(delete(EdgeWorkerModel))

    def test_version(self):
        assert _version("1.2.3") == (1, 2, 3)
        assert _version("1.2.3rc1") == (1, 2, 3)
        assert _version("1.2.3.dev0") == (1, 2, 3)

    def test_assert_version(self):
        from airflow import __version__ as airflow_version
        from airflow.providers.edge3 import __version__ as edge_provider_version

        with pytest.raises(HTTPException):
            _assert_version({})

        with pytest.raises(HTTPException):
            _assert_version({"airflow_version": airflow_version})

        with pytest.raises(HTTPException):
            _assert_version({"edge_provider_version": edge_provider_version})

        with pytest.raises(HTTPException):
            _assert_version({"airflow_version": "1.2.3", "edge_provider_version": edge_provider_version})

        with pytest.raises(HTTPException):
            _assert_version({"airflow_version": airflow_version, "edge_provider_version": "2023.10.07"})

        with conf_vars({("edge", "minimum_acceptable_edge_version_for_workers"): "3.2.0"}):
            with pytest.raises(HTTPException):
                _assert_version({"airflow_version": airflow_version, "edge_provider_version": "3.1.0"})

            _assert_version({"airflow_version": airflow_version, "edge_provider_version": "3.2.0"})
            _assert_version({"airflow_version": airflow_version, "edge_provider_version": "3.2.1rc1"})
            _assert_version({"airflow_version": airflow_version, "edge_provider_version": "4.1.1"})

        with conf_vars({("edge", "minimum_acceptable_core_version_for_workers"): "3.1.0"}):
            with pytest.raises(HTTPException):
                _assert_version({"airflow_version": "3.0.0", "edge_provider_version": edge_provider_version})

            _assert_version({"airflow_version": "3.1.0", "edge_provider_version": edge_provider_version})
            _assert_version({"airflow_version": "3.2.0rc3", "edge_provider_version": edge_provider_version})
            _assert_version({"airflow_version": "4.1.0", "edge_provider_version": edge_provider_version})

        _assert_version({"airflow_version": airflow_version, "edge_provider_version": edge_provider_version})

    @pytest.mark.parametrize(
        "input_queues",
        [
            pytest.param(None, id="empty-queues"),
            pytest.param(["default", "default2"], id="with-queues"),
        ],
    )
    def test_register(self, session: Session, input_queues: list[str] | None, cli_worker: EdgeWorker):
        body = WorkerStateBody(
            state=EdgeWorkerState.STARTING,
            jobs_active=0,
            queues=input_queues,
            sysinfo=self.MOCK_SYSINFO,
        )
        register("test_worker", body, session)
        session.commit()

        worker: Sequence[EdgeWorkerModel] = session.scalars(select(EdgeWorkerModel)).all()
        assert len(worker) == 1
        assert worker[0].worker_name == "test_worker"
        assert worker[0].team_name is None
        if input_queues:
            assert worker[0].queues == input_queues
        else:
            assert worker[0].queues is None

    def test_register_with_team_name(self, session: Session, cli_worker: EdgeWorker):
        body = WorkerStateBody(
            state=EdgeWorkerState.STARTING,
            jobs_active=0,
            queues=["default"],
            sysinfo=self.MOCK_SYSINFO,
            team_name="team_a",
        )
        register("test_worker", body, session)
        session.commit()

        worker: Sequence[EdgeWorkerModel] = session.scalars(select(EdgeWorkerModel)).all()
        assert len(worker) == 1
        assert worker[0].worker_name == "test_worker"
        assert worker[0].team_name == "team_a"

    def test_register_same_name_different_team_rejects_when_active(
        self, session: Session, cli_worker: EdgeWorker
    ):
        """A physical worker (hostname) can only have one identity. Registering the same
        worker_name with a different team_name while the existing one is active should be rejected."""
        existing_worker = EdgeWorkerModel(
            worker_name="test_worker",
            state=EdgeWorkerState.RUNNING,
            queues=["default"],
            first_online=timezone.utcnow(),
            team_name="team_a",
        )
        session.add(existing_worker)
        session.commit()

        body = WorkerStateBody(
            state=EdgeWorkerState.STARTING,
            jobs_active=0,
            queues=["default"],
            sysinfo=self.MOCK_SYSINFO,
            team_name="team_b",
        )
        with pytest.raises(HTTPException) as exc_info:
            register("test_worker", body, session)
        assert exc_info.value.status_code == 409

    def test_register_same_name_different_team_reuses_when_offline(
        self, session: Session, cli_worker: EdgeWorker
    ):
        """When an existing worker with the same name is offline, re-registering with a
        different team_name should succeed and update the team_name."""
        existing_worker = EdgeWorkerModel(
            worker_name="test_worker",
            state=EdgeWorkerState.OFFLINE,
            queues=["default"],
            first_online=timezone.utcnow(),
            team_name="team_a",
        )
        session.add(existing_worker)
        session.commit()

        body = WorkerStateBody(
            state=EdgeWorkerState.STARTING,
            jobs_active=0,
            queues=["default"],
            sysinfo=self.MOCK_SYSINFO,
            team_name="team_b",
        )
        register("test_worker", body, session)
        session.commit()

        worker = session.execute(
            select(EdgeWorkerModel).where(EdgeWorkerModel.worker_name == "test_worker")
        ).scalar_one_or_none()
        assert worker is not None
        assert worker.team_name == "team_b"

    @pytest.mark.parametrize(
        ("existing_state", "should_raise"),
        [
            pytest.param(EdgeWorkerState.RUNNING, True, id="duplicate-running"),
            pytest.param(EdgeWorkerState.IDLE, True, id="duplicate-idle"),
            pytest.param(EdgeWorkerState.STARTING, True, id="duplicate-starting"),
            pytest.param(EdgeWorkerState.TERMINATING, True, id="duplicate-terminating"),
            pytest.param(EdgeWorkerState.MAINTENANCE_MODE, True, id="duplicate-maintenance"),
            pytest.param(EdgeWorkerState.OFFLINE, False, id="reuse-offline"),
            pytest.param(EdgeWorkerState.UNKNOWN, False, id="reuse-unknown"),
            pytest.param(EdgeWorkerState.OFFLINE_MAINTENANCE, False, id="reuse-offline-maintenance"),
        ],
    )
    def test_register_duplicate_worker(
        self, session: Session, existing_state: EdgeWorkerState, should_raise: bool, cli_worker: EdgeWorker
    ):
        # Create an existing worker
        existing_worker = EdgeWorkerModel(
            worker_name="test_worker",
            state=existing_state,
            queues=["default"],
            first_online=timezone.utcnow(),
        )
        session.add(existing_worker)
        session.commit()

        # Try to register a new worker with the same name
        body = WorkerStateBody(
            state=EdgeWorkerState.STARTING,
            jobs_active=0,
            queues=["default"],
            sysinfo=self.MOCK_SYSINFO,
        )

        if should_raise:
            with pytest.raises(HTTPException) as exc_info:
                register("test_worker", body, session)
            assert exc_info.value.status_code == 409
            assert "already active" in str(exc_info.value.detail).lower()
        else:
            # Should succeed for offline/unknown states
            register("test_worker", body, session)
            session.commit()
            worker = session.execute(
                select(EdgeWorkerModel).where(EdgeWorkerModel.worker_name == "test_worker")
            ).scalar_one_or_none()
            assert worker is not None
            # State should be updated (or redefined based on redefine_state logic)
            assert worker.state is not None

    @pytest.mark.parametrize(
        ("worker_state", "body_state", "expected_state"),
        [
            pytest.param(
                EdgeWorkerState.MAINTENANCE_REQUEST,
                EdgeWorkerState.MAINTENANCE_PENDING,
                EdgeWorkerState.MAINTENANCE_PENDING,
                id="stay_maintenance_pending",
            ),
            pytest.param(
                EdgeWorkerState.MAINTENANCE_REQUEST,
                EdgeWorkerState.MAINTENANCE_MODE,
                EdgeWorkerState.MAINTENANCE_MODE,
                id="stay_maintenance_mode",
            ),
            pytest.param(
                EdgeWorkerState.MAINTENANCE_REQUEST,
                EdgeWorkerState.RUNNING,
                EdgeWorkerState.MAINTENANCE_REQUEST,
                id="maintenance_request",
            ),
            pytest.param(
                EdgeWorkerState.MAINTENANCE_EXIT,
                EdgeWorkerState.MAINTENANCE_PENDING,
                EdgeWorkerState.RUNNING,
                id="exit_maintenance_pending",
            ),
            pytest.param(
                EdgeWorkerState.MAINTENANCE_EXIT,
                EdgeWorkerState.MAINTENANCE_MODE,
                EdgeWorkerState.IDLE,
                id="exit_maintenance_mode",
            ),
            pytest.param(
                EdgeWorkerState.MAINTENANCE_EXIT,
                EdgeWorkerState.RUNNING,
                EdgeWorkerState.RUNNING,
                id="no_exit",
            ),
            pytest.param(
                EdgeWorkerState.RUNNING, EdgeWorkerState.IDLE, EdgeWorkerState.IDLE, id="no_maintenance"
            ),
            pytest.param(
                EdgeWorkerState.OFFLINE_MAINTENANCE,
                EdgeWorkerState.STARTING,
                EdgeWorkerState.MAINTENANCE_REQUEST,
                id="maintenance_starting",
            ),
            pytest.param(
                EdgeWorkerState.MAINTENANCE_MODE,
                EdgeWorkerState.STARTING,
                EdgeWorkerState.MAINTENANCE_REQUEST,
                id="maintenance_crash",
            ),
            pytest.param(
                EdgeWorkerState.MAINTENANCE_PENDING,
                EdgeWorkerState.STARTING,
                EdgeWorkerState.MAINTENANCE_REQUEST,
                id="maintenance_crash_2",
            ),
            pytest.param(
                EdgeWorkerState.MAINTENANCE_REQUEST,
                EdgeWorkerState.STARTING,
                EdgeWorkerState.MAINTENANCE_REQUEST,
                id="maintenance_crash_3",
            ),
        ],
    )
    def test_redefine_state(
        self, worker_state: EdgeWorkerState, body_state: EdgeWorkerState, expected_state: EdgeWorkerState
    ):
        from airflow.providers.edge3.worker_api.routes.worker import redefine_state

        assert redefine_state(worker_state, body_state) == expected_state

    def test_set_state(self, session: Session, cli_worker: EdgeWorker):
        queues = ["default", "default2"]
        rwm = EdgeWorkerModel(
            worker_name="test2_worker",
            state=EdgeWorkerState.IDLE,
            queues=queues,
            first_online=timezone.utcnow(),
        )
        session.add(rwm)
        session.commit()

        body = WorkerStateBody(
            state=EdgeWorkerState.RUNNING,
            jobs_active=1,
            queues=["default2"],
            sysinfo=self.MOCK_SYSINFO,
        )
        return_queues = set_state("test2_worker", body, session).queues

        worker: Sequence[EdgeWorkerModel] = session.scalars(select(EdgeWorkerModel)).all()
        assert len(worker) == 1
        assert worker[0].worker_name == "test2_worker"
        assert worker[0].state == EdgeWorkerState.RUNNING
        assert worker[0].queues == queues
        assert return_queues == ["default", "default2"]

    def test_set_state_returns_concurrency(self, session: Session, cli_worker: EdgeWorker):
        """set_state includes the DB-stored concurrency override in its response."""
        rwm = EdgeWorkerModel(
            worker_name="test2_worker",
            state=EdgeWorkerState.IDLE,
            queues=["default"],
            first_online=timezone.utcnow(),
        )
        rwm.concurrency = 16
        session.add(rwm)
        session.commit()

        body = WorkerStateBody(
            state=EdgeWorkerState.RUNNING,
            jobs_active=0,
            queues=["default"],
            sysinfo=self.MOCK_SYSINFO,
        )
        result = set_state("test2_worker", body, session)
        assert result.concurrency == 16

    def test_set_state_returns_none_concurrency_when_not_overridden(
        self, session: Session, cli_worker: EdgeWorker
    ):
        """set_state returns None for concurrency when no override is set."""
        rwm = EdgeWorkerModel(
            worker_name="test2_worker",
            state=EdgeWorkerState.IDLE,
            queues=["default"],
            first_online=timezone.utcnow(),
        )
        session.add(rwm)
        session.commit()

        body = WorkerStateBody(
            state=EdgeWorkerState.RUNNING,
            jobs_active=0,
            queues=["default"],
            sysinfo=self.MOCK_SYSINFO,
        )
        result = set_state("test2_worker", body, session)
        assert result.concurrency is None

    def test_set_worker_concurrency(self, session: Session):
        rwm = EdgeWorkerModel(
            worker_name="test2_worker",
            state=EdgeWorkerState.IDLE,
            queues=["default"],
            first_online=timezone.utcnow(),
        )
        session.add(rwm)
        session.commit()

        set_worker_concurrency("test2_worker", 16, session=session)
        session.commit()

        worker = session.scalars(select(EdgeWorkerModel)).one()
        assert worker.concurrency == 16

    @pytest.mark.parametrize(
        "offline_state",
        [
            pytest.param(EdgeWorkerState.OFFLINE, id="offline"),
            pytest.param(EdgeWorkerState.OFFLINE_MAINTENANCE, id="offline-maintenance"),
            pytest.param(EdgeWorkerState.UNKNOWN, id="unknown"),
        ],
    )
    def test_set_worker_concurrency_rejects_offline(self, session: Session, offline_state: EdgeWorkerState):
        rwm = EdgeWorkerModel(
            worker_name="test2_worker",
            state=offline_state,
            queues=["default"],
            first_online=timezone.utcnow(),
        )
        session.add(rwm)
        session.commit()

        with pytest.raises(TypeError, match="Cannot set concurrency"):
            set_worker_concurrency("test2_worker", 8, session=session)

    def test_set_worker_concurrency_raises_for_unknown_worker(self, session: Session):
        with pytest.raises(ValueError, match="not found"):
            set_worker_concurrency("nonexistent", 8, session=session)

    @pytest.mark.parametrize(
        ("add_queues", "remove_queues", "expected_queues"),
        [
            pytest.param(None, None, ["init"], id="no-changes"),
            pytest.param(
                ["queue1", "queue2"], ["queue1", "queue_not_existing"], ["init", "queue2"], id="add-remove"
            ),
            pytest.param(["init"], None, ["init"], id="check-duplicated"),
        ],
    )
    def test_update_queues(
        self,
        session: Session,
        add_queues: list[str] | None,
        remove_queues: list[str] | None,
        expected_queues: list[str],
    ):
        rwm = EdgeWorkerModel(
            worker_name="test2_worker",
            state=EdgeWorkerState.IDLE,
            queues=["init"],
            first_online=timezone.utcnow(),
        )
        session.add(rwm)
        session.commit()
        body = WorkerQueueUpdateBody(new_queues=add_queues, remove_queues=remove_queues)
        update_queues("test2_worker", body, session)
        worker: Sequence[EdgeWorkerModel] = session.scalars(select(EdgeWorkerModel)).all()
        assert len(worker) == 1
        assert worker[0].worker_name == "test2_worker"
        assert len(expected_queues) == len(worker[0].queues or [])
        for expected_queue in expected_queues:
            assert expected_queue in (worker[0].queues or [])
