"""Data generation service with scheduled tasks."""

import logging
import random
from typing import override

from bson import ObjectId
from mm_http import http_request
from mm_mongo import MongoInsertManyResult, MongoInsertOneResult

from app.core.db import Data, DataStatus
from app.core.types import AppCore
from mm_base6 import Service

logger = logging.getLogger(__name__)


class DataService(Service[AppCore]):
    """Service for generating and inserting data items."""

    @override
    def configure_scheduler(self) -> None:
        """Register scheduled task for periodic data generation."""
        self.core.scheduler.add("generate_one", 60, self.generate_one)

    async def generate_one(self) -> MongoInsertOneResult:
        """Generate and insert a single random data item."""
        status = random.choice(list(DataStatus))
        value = random.randint(0, 1_000_000)
        self.core.services.misc.increment_counter()
        logger.debug("generate_one", extra={"status": status, "value": value})

        return await self.core.db.data.insert_one(Data(id=ObjectId(), status=status, value=value))

    async def generate_many(self) -> MongoInsertManyResult:
        """Generate and insert 10 random data items with logging and notifications."""
        res = await http_request("https://httpbin.org/get", timeout=5)
        await self.core.builtin_services.event.event("generate_many", {"res": res.json_body_or_none(), "large-data": "abc" * 100})
        await self.core.builtin_services.event.event("ddd", self.core.settings.telegram_chat_id)
        await self.core.builtin_services.telegram.send_message("generate_many")
        new_data_list = [
            Data(id=ObjectId(), status=random.choice(list(DataStatus)), value=random.randint(0, 1_000_000)) for _ in range(10)
        ]
        return await self.core.db.data.insert_many(new_data_list)
