import logging

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models.knowledge import KnowledgeManufacturer

logger = logging.getLogger(__name__)

DEFAULT_MANUFACTURERS = [
    "Stabo",
    "President",
    "Albrecht",
    "Marconi",
    "Rohde & Schwarz",
    "HP",
    "CRT",
    "Alinco",
    "Motorola",
    "Team",
]


def _slugify(value: str) -> str:
    normalized = value.strip().lower()
    normalized = normalized.replace("&", "und")
    normalized = normalized.replace("ß", "ss")
    normalized = normalized.replace("ö", "oe")
    normalized = normalized.replace("ä", "ae")
    normalized = normalized.replace("ü", "ue")

    parts = []
    current = []

    for char in normalized:
        if char.isalnum():
            current.append(char)
        elif current:
            parts.append("".join(current))
            current = []

    if current:
        parts.append("".join(current))

    return "-".join(parts)


def seed_knowledge_manufacturers(db: Session) -> None:
    created_count = 0

    existing = {
        manufacturer.name.lower(): manufacturer
        for manufacturer in db.scalars(select(KnowledgeManufacturer)).all()
    }

    for name in DEFAULT_MANUFACTURERS:
        existing_manufacturer = existing.get(name.lower())

        if existing_manufacturer:
            if not existing_manufacturer.slug:
                existing_manufacturer.slug = _slugify(name)
            continue

        manufacturer = KnowledgeManufacturer(
            name=name,
            slug=_slugify(name),
            notes="Systemseitig initial angelegt",
        )
        db.add(manufacturer)
        created_count += 1

    db.commit()

    logger.info(
        "knowledge.manufacturers.seeded",
        extra={"manufacturer_seed_created_count": created_count},
    )
