"""
Platform Worker entrypoint.

Run with: poetry run python -m platform_worker.main

This worker:
- Registers workflows from optovia_workflows package
- Registers activities with service configurations (Odoo, Teams, Logto URLs)
- Handles graceful shutdown on SIGINT/SIGTERM
"""

import asyncio
import logging
import signal
import sys
from concurrent.futures import ThreadPoolExecutor

from temporalio.client import Client
from temporalio.worker import Worker

from optovia_workflows import KycApplicationWorkflow, AddressWorkflow, OfferWorkflow, InviteUserWorkflow

from . import activities
from .config import settings

# Configure structured logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)


async def run_worker() -> None:
    """
    Connect to Temporal and run the worker.

    Handles graceful shutdown on SIGINT/SIGTERM.
    """
    logger.info(
        "Connecting to Temporal at %s (namespace=%s)",
        settings.TEMPORAL_HOST,
        settings.TEMPORAL_NAMESPACE,
    )

    client = await Client.connect(
        settings.TEMPORAL_HOST,
        namespace=settings.TEMPORAL_NAMESPACE,
    )

    logger.info(
        "Starting worker on task queue: %s (max_activities=%d, max_workflow_tasks=%d)",
        settings.TASK_QUEUE,
        settings.MAX_CONCURRENT_ACTIVITIES,
        settings.MAX_CONCURRENT_WORKFLOW_TASKS,
    )

    # ThreadPoolExecutor for synchronous activities (HTTP calls)
    activity_executor = ThreadPoolExecutor(
        max_workers=settings.MAX_CONCURRENT_ACTIVITIES,
        thread_name_prefix="activity-",
    )

    worker = Worker(
        client,
        task_queue=settings.TASK_QUEUE,
        workflows=[KycApplicationWorkflow, AddressWorkflow, OfferWorkflow, InviteUserWorkflow],
        activities=[
            activities.add_kyc_to_odoo,
            activities.set_buyer_logto_org,
            activities.create_logto_org,
            activities.log_kyc_event,
            activities.set_logto_org_id,
            activities.create_offer_in_exchange,
            activities.update_offer_workflow_status,
            activities.save_offer_description,
            activities.trigger_prefect_offer_sync,
            activities.create_invitation,
            activities.create_invitation_token,
            activities.update_invitation_token_status,
            activities.send_invite_notification,
            activities.create_address_in_django,
            activities.update_address_status,
            activities.trigger_prefect_sync,
        ],
        activity_executor=activity_executor,
        max_concurrent_activities=settings.MAX_CONCURRENT_ACTIVITIES,
        max_concurrent_workflow_tasks=settings.MAX_CONCURRENT_WORKFLOW_TASKS,
    )

    # Setup graceful shutdown
    shutdown_event = asyncio.Event()

    def signal_handler(signum: int, frame: object) -> None:
        sig_name = signal.Signals(signum).name
        logger.info("Received %s, initiating graceful shutdown...", sig_name)
        shutdown_event.set()

    # Register signal handlers
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    logger.info("Worker started. Press Ctrl+C to stop.")

    # Run worker with graceful shutdown
    async with worker:
        await shutdown_event.wait()

    logger.info("Worker stopped gracefully.")


def main() -> None:
    """Entry point for poetry script."""
    try:
        asyncio.run(run_worker())
    except KeyboardInterrupt:
        logger.info("Shutdown complete.")
        sys.exit(0)


if __name__ == "__main__":
    main()
