"""
Tests for omnisec.internet.InternetToolkit
"""

import pytest
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from omnisec.internet import InternetToolkit

net = InternetToolkit(timeout=5)


class TestIPValidation:
    def test_private_ip_check(self):
        from omnisec.security import SecurityToolkit
        sec = SecurityToolkit()
        assert sec.is_private_ip("10.0.0.1") is True
        assert sec.is_private_ip("8.8.8.8") is False


class TestPortScan:
    def test_localhost_scan(self):
        result = net.port_scan("127.0.0.1", ports=[80, 443, 9999], timeout=0.5)
        assert "host" in result
        assert "open_ports" in result
        assert "total_scanned" in result
        assert result["total_scanned"] == 3

    def test_result_structure(self):
        result = net.port_scan("127.0.0.1", ports=[9999], timeout=0.3)
        assert isinstance(result["open_ports"], list)
        assert isinstance(result["closed_count"], int)
        assert isinstance(result["duration_sec"], float)


class TestDNS:
    def test_dns_resolve_localhost(self):
        result = net.dns_resolve("localhost", "A")
        assert isinstance(result, list)

    def test_reverse_dns_loopback(self):
        result = net.reverse_dns("127.0.0.1")
        assert result is not None


class TestSSL:
    def test_ssl_info_structure(self):
        try:
            cert = net.ssl_info("google.com")
            assert "days_remaining" in cert
            assert "issuer" in cert
            assert "valid_until" in cert
            assert cert["days_remaining"] > 0
        except Exception:
            pytest.skip("Network not available")


class TestLinkExtraction:
    def test_extract_absolute_links(self):
        html = '<a href="https://example.com">link</a> <a href="https://test.org/page">test</a>'
        links = net.extract_links(html)
        assert "https://example.com" in links
        assert "https://test.org/page" in links

    def test_extract_relative_links(self):
        html = '<a href="/about">About</a>'
        links = net.extract_links(html, base_url="https://example.com")
        assert "https://example.com/about" in links

    def test_no_duplicates(self):
        html = '<a href="https://a.com">1</a><a href="https://a.com">2</a>'
        links = net.extract_links(html)
        assert links.count("https://a.com") == 1


class TestServiceNames:
    def test_known_ports(self):
        assert net._get_service_name(22) == "SSH"
        assert net._get_service_name(80) == "HTTP"
        assert net._get_service_name(443) == "HTTPS"
        assert net._get_service_name(3306) == "MySQL"

    def test_unknown_port(self):
        assert net._get_service_name(9999) == "unknown"


class TestInternetToolkitRepr:
    def test_repr(self):
        r = repr(net)
        assert "InternetToolkit" in r
        assert "timeout" in r


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
