<?php

namespace Antimanual;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class GenerationJobWorker {
    public function __construct() {
        add_action( 'atml_process_generation_job', [ $this, 'process_job' ], 10, 1 );
    }

    public function process_job( $job_id ) {
        if ( empty( $job_id ) ) {
            return;
        }

        $job = GenerationJobs::get( $job_id );
        if ( ! $job ) {
            return;
        }

        // If already processing or completed, skip.
        if ( isset( $job['status'] ) && in_array( $job['status'], array( 'processing', 'completed' ), true ) ) {
            return;
        }

        // Claim the job.
        $attempts = intval( $job['attempts'] ?? 0 ) + 1;
        GenerationJobs::update( $job_id, array(
            'status'     => 'processing',
            'attempts'   => $attempts,
            'started_at' => current_time( 'mysql' ),
        ) );

        $params = $job['params'] ?? array();

        try {
            $result = PostGenerator::generate( $params );

            if ( is_wp_error( $result ) ) {
                throw new \Exception( $result->get_error_message() );
            }

            $summary = '';
            if ( is_array( $result ) && ! empty( $result['content'] ) ) {
                $summary = wp_trim_words( wp_strip_all_tags( $result['content'] ), 50 );
            }

            GenerationJobs::update( $job_id, array(
                'status'      => 'completed',
                'executed_at' => current_time( 'mysql' ),
                'result'      => array(
                    'post_id'  => $result['post_id'] ?? null,
                    'title'    => $result['title'] ?? null,
                    'slug'     => $result['slug'] ?? null,
                    'excerpt'  => $result['excerpt'] ?? null,
                    'summary'  => $summary,
                    'warnings' => is_array( $result['warnings'] ?? null ) ? $result['warnings'] : array(),
                ),
            ) );

        } catch ( \Throwable $e ) {
            error_log( '[Antimanual] Generation job ' . $job_id . ' failed: ' . $e->getMessage() );

            $max_attempts = 3;

            if ( $attempts < $max_attempts ) {
                $delay = pow( 2, $attempts ) * 60;

                GenerationJobs::update( $job_id, array(
                    'status'     => 'pending',
                    'last_error' => $e->getMessage(),
                ) );

                wp_schedule_single_event( time() + $delay, 'atml_process_generation_job', array( $job_id ) );
                if ( function_exists( 'spawn_cron' ) ) {
                    spawn_cron();
                }
            } else {
                GenerationJobs::update( $job_id, array(
                    'status'      => 'failed',
                    'last_error'  => $e->getMessage(),
                    'executed_at' => current_time( 'mysql' ),
                ) );
            }
        }
    }
}

new GenerationJobWorker();
