<?php
/**
 * LuxStrat Deduplication Guard
 *
 * Prevents duplicate Luxembourg structuring posts:
 *   - Max 1 post per theme per week (Sunday cycle)
 *   - Max 1 post per Sunday total (single post per run)
 *   - Title similarity check against recent posts
 *
 * @package DamalionBlogAI
 * @subpackage LuxStrat
 */

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

class DBA_LuxStrat_Dedupe {

    /** Meta key prefix for all LuxStrat posts */
    const META_PREFIX = '_dba_luxstrat_';

    /**
     * Check if a theme already has a post this week (Mon→Sun).
     *
     * @param  string $theme_slug  Theme key from the registry.
     * @return bool   True if a post already exists this week for this theme.
     */
    public static function theme_posted_this_week( $theme_slug ) {
        if ( empty( $theme_slug ) ) {
            return false;
        }

        $tz = self::get_timezone();
        $now = new DateTime( 'now', $tz );

        // Get the Monday of the current week
        $day_of_week = (int) $now->format( 'N' ); // 1=Mon, 7=Sun
        $monday = clone $now;
        $monday->modify( '-' . ( $day_of_week - 1 ) . ' days' );
        $week_start = $monday->format( 'Y-m-d' ) . ' 00:00:00';
        $week_end   = $now->format( 'Y-m-d' ) . ' 23:59:59';

        $existing = new WP_Query( array(
            'post_type'      => 'post',
            'post_status'    => array( 'publish', 'draft', 'pending', 'private' ),
            'posts_per_page' => 1,
            'fields'         => 'ids',
            'date_query'     => array(
                array(
                    'after'     => $week_start,
                    'before'    => $week_end,
                    'inclusive' => true,
                ),
            ),
            'meta_query'     => array(
                'relation' => 'AND',
                array(
                    'key'     => self::META_PREFIX . 'auto_created',
                    'compare' => 'EXISTS',
                ),
                array(
                    'key'     => self::META_PREFIX . 'theme',
                    'value'   => $theme_slug,
                    'compare' => '=',
                ),
            ),
            'no_found_rows'          => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        ) );

        return $existing->have_posts();
    }

    /**
     * Check if ANY LuxStrat post was already published today.
     *
     * @return bool
     */
    public static function posted_today() {
        $tz  = self::get_timezone();
        $now = new DateTime( 'now', $tz );
        $today_start = $now->format( 'Y-m-d' ) . ' 00:00:00';
        $today_end   = $now->format( 'Y-m-d' ) . ' 23:59:59';

        $existing = new WP_Query( array(
            'post_type'      => 'post',
            'post_status'    => array( 'publish', 'draft', 'pending', 'private' ),
            'posts_per_page' => 1,
            'fields'         => 'ids',
            'date_query'     => array(
                array(
                    'after'     => $today_start,
                    'before'    => $today_end,
                    'inclusive' => true,
                ),
            ),
            'meta_query'     => array(
                array(
                    'key'     => self::META_PREFIX . 'auto_created',
                    'compare' => 'EXISTS',
                ),
            ),
            'no_found_rows'          => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        ) );

        return $existing->have_posts();
    }

    /**
     * Check if a title is too similar to recent LuxStrat posts (last 90 days).
     *
     * @param  string $title Proposed post title.
     * @return bool   True if a similar title exists.
     */
    public static function title_is_duplicate( $title ) {
        if ( empty( $title ) ) {
            return false;
        }

        $normalised = mb_strtolower( trim( $title ) );

        $recent = new WP_Query( array(
            'post_type'      => 'post',
            'post_status'    => array( 'publish', 'draft', 'pending', 'private' ),
            'posts_per_page' => 100,
            'fields'         => 'ids',
            'date_query'     => array(
                array(
                    'after' => '90 days ago',
                ),
            ),
            'meta_query'     => array(
                array(
                    'key'     => self::META_PREFIX . 'auto_created',
                    'compare' => 'EXISTS',
                ),
            ),
            'no_found_rows'          => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        ) );

        if ( ! $recent->have_posts() ) {
            return false;
        }

        foreach ( $recent->posts as $post_id ) {
            $existing_title = mb_strtolower( trim( get_the_title( $post_id ) ) );
            // Exact match
            if ( $existing_title === $normalised ) {
                return true;
            }
            // High similarity (>85%)
            similar_text( $normalised, $existing_title, $percent );
            if ( $percent > 85 ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Fast in-memory tracker (transient) to prevent double-runs on the same day.
     *
     * @param  string $theme_slug
     * @return bool   True if already marked.
     */
    public static function is_marked_today( $theme_slug ) {
        $key  = 'dba_luxstrat_used_' . date( 'Y-m-d' );
        $used = get_transient( $key );
        if ( ! is_array( $used ) ) {
            return false;
        }
        return in_array( $theme_slug, $used, true );
    }

    /**
     * Mark a theme as used today in transient.
     *
     * @param string $theme_slug
     */
    public static function mark_used_today( $theme_slug ) {
        $key  = 'dba_luxstrat_used_' . date( 'Y-m-d' );
        $used = get_transient( $key );
        if ( ! is_array( $used ) ) {
            $used = array();
        }
        if ( ! in_array( $theme_slug, $used, true ) ) {
            $used[] = $theme_slug;
            set_transient( $key, $used, DAY_IN_SECONDS );
        }
    }

    /**
     * Get Luxembourg timezone object.
     *
     * @return DateTimeZone
     */
    private static function get_timezone() {
        try {
            return new DateTimeZone( 'Europe/Luxembourg' );
        } catch ( \Exception $e ) {
            return new DateTimeZone( 'UTC' );
        }
    }
}
