from __future__ import annotations

import asyncio
import os
import logging
from temporalio.client import Client
from temporalio.worker import Worker

from ops_agent.temporal.workflows import OpsRemediateWorkflow
from ops_agent.temporal.activities import (
    run_ops_diagnose_activity,
    run_ops_remediate_activity
)

# Configure logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

async def _main() -> None:
    address = os.environ.get("TEMPORAL_ADDRESS", "temporal-frontend.ai-core.svc.cluster.local:7233")
    namespace = os.environ.get("TEMPORAL_NAMESPACE", "default")
    task_queue = os.environ.get("OPS_TASK_QUEUE", "ops")

    logger.info(f"Connecting to Temporal cluster at {address} (Namespace: {namespace})...")
    try:
        client = await Client.connect(address, namespace=namespace)
        logger.info("Successfully connected to Temporal!")
    except Exception as e:
        logger.error(f"Failed to connect to Temporal: {e}")
        return

    worker = Worker(
        client,
        task_queue=task_queue,
        workflows=[OpsRemediateWorkflow],
        activities=[
            run_ops_diagnose_activity,
            run_ops_remediate_activity,
        ],
    )
    logger.info(f"Starting OpsAgent worker on queue '{task_queue}'...")
    await worker.run()

def main() -> None:
    asyncio.run(_main())

if __name__ == "__main__":
    main()
