"""Tests for connection auto-discovery module."""

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "backend"))

from discovery.odbc_discovery import (
    ConnectionDiscovery,
    _guess_db_type,
    _guess_source_system,
    _build_connection_string,
    discover_dbeaver,
)


class TestGuessDbType:
    def test_sql_server(self):
        assert _guess_db_type("ODBC Driver 17 for SQL Server") == "sqlserver"

    def test_sql_server_variant(self):
        assert _guess_db_type("SQL Server Native Client 11.0") == "sqlserver"

    def test_hana(self):
        assert _guess_db_type("HDBODBC") == "hana"

    def test_hana_variant(self):
        assert _guess_db_type("SAP HANA ODBC Driver") == "hana"

    def test_postgresql(self):
        assert _guess_db_type("PostgreSQL Unicode") == "postgresql"

    def test_mysql(self):
        assert _guess_db_type("MySQL ODBC 8.0") == "mysql"

    def test_unknown(self):
        assert _guess_db_type("Something Random") == "unknown"

    def test_mssql_jdbc(self):
        assert _guess_db_type("mssql_jdbc_ms_new") == "sqlserver"


class TestGuessSourceSystem:
    def test_ecc(self):
        assert _guess_source_system("SAP ECC Production", "sqlserver") == "sap_ecc"

    def test_b1(self):
        assert _guess_source_system("Business One Dev", "hana") == "sap_b1"

    def test_hana_defaults_to_b1(self):
        assert _guess_source_system("Production DB", "hana") == "sap_b1"

    def test_infor(self):
        assert _guess_source_system("Infor M3", "sqlserver") == "infor"

    def test_hubspot(self):
        assert _guess_source_system("HubSpot Export", "postgresql") == "hubspot"

    def test_unknown(self):
        assert _guess_source_system("My Database", "sqlserver") == ""


class TestBuildConnectionString:
    def test_sqlserver(self):
        result = _build_connection_string({
            "db_type": "sqlserver",
            "server": "myserver\\SQLEXPRESS",
            "database": "MyDB",
        })
        assert "DRIVER=" in result
        assert "SERVER=myserver\\SQLEXPRESS" in result
        assert "DATABASE=MyDB" in result
        assert "{username}" in result
        assert "{password}" in result

    def test_hana(self):
        result = _build_connection_string({
            "db_type": "hana",
            "server": "hana01.local",
            "port": "30015",
        })
        assert "HDBODBC" in result
        assert "hana01.local:30015" in result

    def test_postgresql(self):
        result = _build_connection_string({
            "db_type": "postgresql",
            "server": "localhost",
            "port": "5432",
            "database": "mydb",
        })
        assert result == "postgresql://localhost:5432/mydb"

    def test_dsn_fallback(self):
        result = _build_connection_string({
            "db_type": "unknown",
            "dsn_name": "MyDSN",
        })
        assert "DSN=MyDSN" in result


class TestFillCredentials:
    def test_fill(self):
        template = "DRIVER={SQL Server};SERVER=x;UID={username};PWD={password}"
        result = ConnectionDiscovery.fill_credentials(template, "admin", "secret123")
        assert "UID=admin" in result
        assert "PWD=secret123" in result
        assert "{username}" not in result
        assert "{password}" not in result


class TestDeduplicate:
    def test_dedup_by_server(self):
        connections = [
            {"name": "A", "source": "ODBC DSN", "server": "server1", "database": "db1"},
            {"name": "B", "source": "DBeaver", "server": "server1", "database": "db1"},
        ]
        result = ConnectionDiscovery._deduplicate(connections)
        assert len(result) == 1
        # DBeaver has higher priority
        assert result[0]["source"] == "DBeaver"

    def test_different_dbs_kept(self):
        connections = [
            {"name": "A", "source": "ODBC DSN", "server": "server1", "database": "db1"},
            {"name": "B", "source": "ODBC DSN", "server": "server1", "database": "db2"},
        ]
        result = ConnectionDiscovery._deduplicate(connections)
        assert len(result) == 2


class TestDiscoverDbeaver:
    def test_returns_list(self):
        """discover_dbeaver returns a list even when DBeaver is not installed."""
        result = discover_dbeaver()
        assert isinstance(result, list)
