"""Tests for symbol registry validation and seed data."""
import pytest
from pydantic import ValidationError

# Import after path setup
from services.symbol_registry.app import VALID_SOURCE_TYPES, CompanyCreate, SourceCreate
from services.symbol_registry.seed import ALIASES, COMPANIES, SOURCES_PER_COMPANY

# --- CompanyCreate validation ---

def test_ticker_uppercased():
    c = CompanyCreate(ticker="aapl", legal_name="Apple Inc.")
    assert c.ticker == "AAPL"


def test_ticker_strips_whitespace():
    c = CompanyCreate(ticker="  MSFT  ", legal_name="Microsoft")
    assert c.ticker == "MSFT"


def test_ticker_rejects_numbers():
    with pytest.raises(ValidationError):
        CompanyCreate(ticker="123", legal_name="Bad")


def test_ticker_rejects_empty():
    with pytest.raises(ValidationError):
        CompanyCreate(ticker="", legal_name="Bad")


def test_ticker_rejects_too_long():
    with pytest.raises(ValidationError):
        CompanyCreate(ticker="ABCDEFGHIJK", legal_name="Bad")


def test_ticker_rejects_special_chars():
    with pytest.raises(ValidationError):
        CompanyCreate(ticker="AA-PL", legal_name="Bad")


# --- SourceCreate validation ---

def test_source_valid_types():
    for st in VALID_SOURCE_TYPES:
        s = SourceCreate(source_type=st, source_name="test")
        assert s.source_type == st


def test_source_rejects_invalid_type():
    with pytest.raises(ValidationError):
        SourceCreate(source_type="invalid_type", source_name="test")


def test_source_rejects_invalid_access_policy():
    with pytest.raises(ValidationError):
        SourceCreate(source_type="market_api", source_name="test", access_policy="secret")


def test_source_validates_config_url():
    s = SourceCreate(
        source_type="market_api",
        source_name="test",
        config={"base_url": "https://api.example.com"},
    )
    assert s.config["base_url"] == "https://api.example.com"


def test_source_rejects_bad_config_url():
    with pytest.raises(ValidationError):
        SourceCreate(
            source_type="market_api",
            source_name="test",
            config={"base_url": "not-a-url"},
        )


# --- Seed data integrity ---

def test_seed_companies_have_required_fields():
    for c in COMPANIES:
        assert c["ticker"]
        assert c["legal_name"]
        assert c["exchange"]
        assert c["sector"]


def test_seed_companies_unique_tickers():
    tickers = [c["ticker"] for c in COMPANIES]
    assert len(tickers) == len(set(tickers))


def test_seed_aliases_reference_valid_tickers():
    tickers = {c["ticker"] for c in COMPANIES}
    for ticker in ALIASES:
        assert ticker in tickers, f"Alias references unknown ticker: {ticker}"


def test_seed_sources_have_valid_types():
    for src in SOURCES_PER_COMPANY:
        assert src["source_type"] in VALID_SOURCE_TYPES


def test_seed_has_ten_companies():
    assert len(COMPANIES) == 50
