import asyncio
import os

import pytest

os.environ.setdefault("APP_SECRET", "test-only-secret-that-is-longer-than-32-characters")
os.environ.setdefault("DATABASE_URL", "sqlite+aiosqlite:///./test.sqlite3")
os.environ.setdefault("REDIS_URL", "redis://localhost:6379/15")
os.environ.setdefault("OWNER_BOOTSTRAP_TOKEN", "test-bootstrap-token-that-is-longer-than-32-characters")
os.environ.setdefault("AI_SERVICE_TOKEN", "test-ai-service-token-that-is-longer-than-32-characters")
os.environ.setdefault("DATA_ENCRYPTION_KEY", "a2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2s=")


class InMemoryRedis:
    def __init__(self):
        self.counters = {}

    async def eval(self, _script, _numkeys, key, _window):
        self.counters[key] = self.counters.get(key, 0) + 1
        return self.counters[key]

    async def ping(self):
        return True

    async def delete(self, *names):
        deleted = 0
        for name in names:
            if name in self.counters:
                deleted += 1
                del self.counters[name]
        return deleted

    async def aclose(self):
        return None


@pytest.fixture
def auth_client(tmp_path):
    from app.database import get_session
    from app.health import get_ai_health_probe, get_redis_client
    from app.main import app
    from app.models import Base, InstallationState
    from fastapi.testclient import TestClient
    from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine

    database_file = tmp_path / "auth.sqlite3"
    engine = create_async_engine(f"sqlite+aiosqlite:///{database_file}")
    session_factory = async_sessionmaker(engine, expire_on_commit=False)

    async def initialize():
        async with engine.begin() as connection:
            await connection.run_sync(Base.metadata.create_all)
        async with session_factory() as session:
            session.add(InstallationState(id=1, owner_setup_completed=False))
            await session.commit()

    async def override_session():
        async with session_factory() as session:
            yield session

    rate_limiter = InMemoryRedis()

    async def override_redis():
        yield rate_limiter

    class HealthyAIProbe:
        async def status(self):
            return "unconfigured"

    asyncio.run(initialize())
    app.dependency_overrides[get_session] = override_session
    app.dependency_overrides[get_redis_client] = override_redis
    app.dependency_overrides[get_ai_health_probe] = lambda: HealthyAIProbe()
    with TestClient(
        app, headers={"x-bootstrap-token": os.environ["OWNER_BOOTSTRAP_TOKEN"]}
    ) as client:
        client.session_factory = session_factory
        yield client
    app.dependency_overrides.clear()
    asyncio.run(engine.dispose())
