import pytest
from sqlalchemy import select
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine

import app.models  # noqa: F401
from app.database import Base
from app.models.skill import Skill
from app.models.user import User
from app.services.admin_bootstrap_service import ensure_builtin_skills
from app.services.auth_service import get_password_hash


@pytest.mark.asyncio
async def test_ensure_builtin_skills_creates_default_ability_skills(tmp_path):
    db_path = tmp_path / 'test_builtin_skills.db'
    engine = create_async_engine(f"sqlite+aiosqlite:///{db_path}", future=True)
    session_factory = async_sessionmaker(engine, expire_on_commit=False)

    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    async with session_factory() as session:
        user = User(
            username='bootstrap_user',
            email='bootstrap@example.com',
            hashed_password=get_password_hash('secret123'),
            full_name='Bootstrap User',
            is_active=True,
            is_superuser=True,
        )
        session.add(user)
        await session.commit()

    async with session_factory() as session:
        await ensure_builtin_skills(session)
        await ensure_builtin_skills(session)
        result = await session.execute(select(Skill).order_by(Skill.agent_type, Skill.name))
        skills = result.scalars().all()

    assert len(skills) >= 9
    assert any(skill.agent_type == 'schedule_planner' for skill in skills)
    assert any(skill.agent_type == 'executor' for skill in skills)
    assert any(skill.agent_type == 'librarian' for skill in skills)
    librarian_skill = next(skill for skill in skills if skill.name == '知识检索摘要')
    assert 'web_search' in (librarian_skill.tools or [])
    assert any(skill.agent_type == 'analyst' for skill in skills)
    assert len({skill.name for skill in skills}) == len(skills)

    await engine.dispose()
