"""Tests for the UniversalScanner.

Validates:
- Local model scanning (filesystem-based)
- Empty result when no models exist
- Host/port parsing utility
"""

from __future__ import annotations

from unittest.mock import patch

import pytest

from llmhosts.discovery.scanner import UniversalScanner

# ---------------------------------------------------------------------------
# Scanner tests (filesystem-based model discovery)
# ---------------------------------------------------------------------------


@pytest.mark.unit
async def test_scanner_returns_engine_when_models_exist() -> None:
    """Scanner should return a single llmhosts-core engine with local models."""
    scanner = UniversalScanner()

    with patch("llmhosts.models.download.list_local_models", return_value=["qwen3:8b", "llama3.3:70b"]):
        engines = await scanner.scan()

    assert len(engines) == 1
    assert engines[0].engine_type == "llmhosts-core"
    assert len(engines[0].models) == 2
    assert engines[0].models[0].id == "qwen3:8b"
    assert engines[0].models[1].id == "llama3.3:70b"
    assert engines[0].confidence == 1.0


@pytest.mark.unit
async def test_scanner_empty_when_no_models() -> None:
    """Scanner should return empty list when no models are downloaded."""
    scanner = UniversalScanner()

    with patch("llmhosts.models.download.list_local_models", return_value=[]):
        engines = await scanner.scan()

    assert engines == []


@pytest.mark.unit
async def test_scanner_single_model() -> None:
    """Scanner should work with a single model."""
    scanner = UniversalScanner()

    with patch("llmhosts.models.download.list_local_models", return_value=["qwen3:1.7b"]):
        engines = await scanner.scan()

    assert len(engines) == 1
    assert len(engines[0].models) == 1
    assert engines[0].models[0].id == "qwen3:1.7b"


# ---------------------------------------------------------------------------
# URL parsing utility
# ---------------------------------------------------------------------------


@pytest.mark.unit
def test_parse_host_port_basic() -> None:
    """Parse basic host:port string."""
    host, port = UniversalScanner._parse_host_port("192.168.1.50:5000")
    assert host == "192.168.1.50"
    assert port == 5000


@pytest.mark.unit
def test_parse_host_port_with_http_prefix() -> None:
    """Parse http://host:port URL."""
    host, port = UniversalScanner._parse_host_port("http://localhost:8080")
    assert host == "localhost"
    assert port == 8080


@pytest.mark.unit
def test_parse_host_port_invalid() -> None:
    """Invalid input should return empty string and 0."""
    host, port = UniversalScanner._parse_host_port("not-a-url")
    assert host == ""
    assert port == 0
