"""Seed the 6 canonical domains and topics from canon/projects/."""
import asyncio
import sys
from pathlib import Path

# Allow running from state-hub/ root
sys.path.insert(0, str(Path(__file__).parent.parent))

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from api.database import async_session_factory, engine
from api.models.domain import Domain
from api.models.topic import Topic, TopicStatus

DOMAINS = [
    {"slug": "custodian", "name": "The Custodian"},
    {"slug": "railiance", "name": "Railiance"},
    {"slug": "markitect", "name": "Markitect"},
    {"slug": "coulomb_social", "name": "Coulomb.social"},
    {"slug": "personhood", "name": "Personhood"},
    {"slug": "foerster_capabilities", "name": "Foerster Capabilities"},
]

TOPICS = [
    {
        "slug": "custodian",
        "title": "The Custodian",
        "description": (
            "Master agent system: transgenerational cognitive infrastructure for "
            "co-creating and stewarding knowledge across all domains."
        ),
        "domain_slug": "custodian",
    },
    {
        "slug": "railiance",
        "title": "Railiance",
        "description": (
            "DevOps & infrastructure reliability. Dependency for all other projects; "
            "provides the deployment and operational backbone."
        ),
        "domain_slug": "railiance",
    },
    {
        "slug": "markitect",
        "title": "Markitect",
        "description": (
            "Knowledge artifact management: structured authoring, versioning, and "
            "retrieval of canonical documents."
        ),
        "domain_slug": "markitect",
    },
    {
        "slug": "coulomb-social",
        "title": "Coulomb.social",
        "description": (
            "Co-creation marketplace experiment: connecting people around shared "
            "projects and complementary capabilities."
        ),
        "domain_slug": "coulomb_social",
    },
    {
        "slug": "personhood",
        "title": "Personhood",
        "description": (
            "Rights and obligations framework: defining digital personhood, consent "
            "models, and data sovereignty."
        ),
        "domain_slug": "personhood",
    },
    {
        "slug": "foerster-capabilities",
        "title": "Foerster Capabilities",
        "description": (
            "Agency capability taxonomy inspired by Heinz von Foerster: mapping the "
            "space of possible cognitive and social actions."
        ),
        "domain_slug": "foerster_capabilities",
    },
]


async def seed() -> None:
    async with async_session_factory() as session:
        # ── Upsert domains ────────────────────────────────────────────────────
        domain_by_slug: dict[str, Domain] = {}
        for data in DOMAINS:
            existing = await session.execute(
                select(Domain).where(Domain.slug == data["slug"])
            )
            domain = existing.scalar_one_or_none()
            if domain is not None:
                if domain.name != data["name"]:
                    domain.name = data["name"]
                    print(f"  update domain: {data['slug']}")
                else:
                    print(f"  skip domain (no change): {data['slug']}")
            else:
                domain = Domain(slug=data["slug"], name=data["name"])
                session.add(domain)
                await session.flush()  # get the id
                print(f"  insert domain: {data['slug']}")
            domain_by_slug[data["slug"]] = domain

        # ── Upsert topics ─────────────────────────────────────────────────────
        for data in TOPICS:
            existing = await session.execute(
                select(Topic).where(Topic.slug == data["slug"])
            )
            topic = existing.scalar_one_or_none()
            domain = domain_by_slug[data["domain_slug"]]
            if topic is not None:
                changed = False
                if topic.title != data["title"]:
                    topic.title = data["title"]
                    changed = True
                if topic.description != data["description"]:
                    topic.description = data["description"]
                    changed = True
                if topic.domain_id != domain.id:
                    topic.domain_id = domain.id
                    changed = True
                print(f"  {'update' if changed else 'skip'} topic ({'changed' if changed else 'no change'}): {data['slug']}")
            else:
                topic = Topic(
                    slug=data["slug"],
                    title=data["title"],
                    description=data["description"],
                    domain_id=domain.id,
                    status=TopicStatus.active,
                )
                session.add(topic)
                print(f"  insert topic: {data['slug']}")

        await session.commit()
    await engine.dispose()
    print("Seed complete.")


if __name__ == "__main__":
    asyncio.run(seed())
