"""
ECS worker entrypoint.

Single Responsibility: Poll SQS and delegate to JobProcessor.
"""

import os
import sys
import time

from ..clients.dynamodb_client import DynamoDBClient
from ..clients.s3_client import S3Client
from ..clients.sqs_client import SQSClient
from .config_downloader import ConfigDownloader
from .error_handler import ErrorHandler
from .job_processor import JobProcessor
from .stage_registry import StageRegistry
from .status_updater import StatusUpdater


def create_worker() -> tuple[JobProcessor, SQSClient]:
    """
    Create worker with all dependencies.

    Initializes all services with dependency injection.

    Returns:
        Tuple of (JobProcessor, SQSClient)

    Raises:
        ValueError: If required environment variables missing
    """
    # Get environment variables
    region = os.getenv("AWS_REGION", "us-east-1")
    dynamodb_table = os.getenv("DYNAMODB_TABLE_NAME")
    sqs_queue_url = os.getenv("SQS_QUEUE_URL")
    s3_bucket = os.getenv("CZBILLGEN_S3_BUCKET")

    if not dynamodb_table:
        raise ValueError("DYNAMODB_TABLE_NAME environment variable required")
    if not sqs_queue_url:
        raise ValueError("SQS_QUEUE_URL environment variable required")
    if not s3_bucket:
        raise ValueError("CZBILLGEN_S3_BUCKET environment variable required")

    # Initialize clients
    dynamodb_client = DynamoDBClient(dynamodb_table, region)
    sqs_client = SQSClient(sqs_queue_url, region)
    s3_client = S3Client(s3_bucket, region)

    # Initialize services
    status_updater = StatusUpdater(dynamodb_client)
    config_downloader = ConfigDownloader(s3_client)
    stage_registry = StageRegistry()
    error_handler = ErrorHandler(status_updater)

    # Create job processor
    job_processor = JobProcessor(
        status_updater=status_updater,
        config_downloader=config_downloader,
        stage_registry=stage_registry,
        error_handler=error_handler,
        sqs_client=sqs_client,
    )

    return job_processor, sqs_client


def process_messages(
    job_processor: JobProcessor, sqs_client: SQSClient
) -> None:
    """
    Poll SQS and process messages in infinite loop.

    Args:
        job_processor: Job processor instance
        sqs_client: SQS client for polling

    Note:
        Runs forever until interrupted or container stopped.
    """
    print("Worker starting - polling for messages...")

    while True:
        try:
            # Poll SQS with long polling (20 seconds)
            messages = sqs_client.receive_messages(
                max_messages=1, wait_time=20
            )

            if not messages:
                # No messages available
                print("No messages in queue, waiting...")
                continue

            # Process each message
            for message in messages:
                receipt_handle = message["ReceiptHandle"]

                try:
                    # Process job with receipt handle for visibility heartbeat
                    job_processor.process_job(message, receipt_handle)

                    # Delete message on success
                    sqs_client.delete_message(receipt_handle)
                    print("Message deleted from queue")

                except Exception as e:
                    # Error handler already updated DynamoDB with failure status
                    # Delete message to unblock queue (no auto-retry via SQS)
                    # Users can manually resubmit failed jobs after fixing issues
                    print(f"ERROR: Job processing failed: {e}")
                    sqs_client.delete_message(receipt_handle)
                    print(
                        "Message deleted from queue (job marked as failed in DynamoDB)"
                    )

        except KeyboardInterrupt:
            print("\nWorker shutting down (interrupted)...")
            break
        except Exception as e:
            print(f"ERROR: Worker loop error: {e}")
            print("Retrying in 10 seconds...")
            time.sleep(10)


def main() -> None:
    """
    Worker entrypoint.

    Creates worker and starts message processing loop.
    """
    print("=" * 60)
    print("CZBG Worker Starting")
    print("=" * 60)
    print(f"DynamoDB Table: {os.getenv('DYNAMODB_TABLE_NAME')}")
    print(f"SQS Queue: {os.getenv('SQS_QUEUE_URL')}")
    print(f"S3 Bucket: {os.getenv('CZBILLGEN_S3_BUCKET')}")
    print(f"AWS Region: {os.getenv('AWS_REGION', 'us-east-1')}")
    print("=" * 60)

    try:
        # Create worker
        job_processor, sqs_client = create_worker()

        # Start processing
        process_messages(job_processor, sqs_client)

    except ValueError as e:
        print(f"ERROR: Configuration error: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"ERROR: Worker startup failed: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
