<?php
/**
 * Breaking News Mode — LiveBlog schema workflow with auto-expire and optional frontend badge.
 *
 * Replaces the editor "LiveBlogPosting" checkbox: sets `_newsai_enable_liveblog` for schema
 * plus `_newsai_breaking_*` meta for expiry and UI state.
 *
 * @package Newsroom_AI_Assistant
 */

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

if ( ! function_exists( 'newsai_breaking_meta_keys' ) ) {
	function newsai_breaking_meta_keys() {
		return [
			'active'  => '_newsai_breaking_active',
			'started' => '_newsai_breaking_started',
			'expires' => '_newsai_breaking_expires',
			'liveblog' => '_newsai_enable_liveblog',
		];
	}
}

if ( ! function_exists( 'newsai_breaking_default_hours' ) ) {
	function newsai_breaking_default_hours() {
		$h = (int) get_option( 'newsai_breaking_expire_hours', 48 );
		if ( ! in_array( $h, [ 24, 48, 72 ], true ) ) {
			$h = 48;
		}
		return $h;
	}
}

if ( ! function_exists( 'newsai_breaking_badge_enabled' ) ) {
	function newsai_breaking_badge_enabled() {
		return get_option( 'newsai_breaking_badge_enabled', 'yes' ) === 'yes';
	}
}

if ( ! function_exists( 'newsai_breaking_liveblog_globally_enabled' ) ) {
	function newsai_breaking_liveblog_globally_enabled() {
		return get_option( 'newsai_liveblog_schema_enabled', 'yes' ) === 'yes';
	}
}

if ( ! function_exists( 'newsai_breaking_deactivate' ) ) {
	/**
	 * End breaking coverage: clear breaking meta and LiveBlog schema flag.
	 *
	 * @param int  $post_id  Post ID.
	 * @param bool $expired  True when auto-expire fired.
	 */
	function newsai_breaking_deactivate( $post_id, $expired = false ) {
		$post_id = (int) $post_id;
		if ( $post_id < 1 ) {
			return;
		}
		$keys = newsai_breaking_meta_keys();
		delete_post_meta( $post_id, $keys['active'] );
		delete_post_meta( $post_id, $keys['started'] );
		delete_post_meta( $post_id, $keys['expires'] );
		delete_post_meta( $post_id, $keys['liveblog'] );
		if ( function_exists( 'nros_clear_schema_cache_on_save' ) ) {
			nros_clear_schema_cache_on_save( $post_id );
		}
		do_action( 'newsai_breaking_deactivated', $post_id, $expired );
	}
}

if ( ! function_exists( 'newsai_breaking_activate' ) ) {
	/**
	 * @param int      $post_id Post ID.
	 * @param int|null $hours   Override expire hours (24|48|72).
	 */
	function newsai_breaking_activate( $post_id, $hours = null ) {
		$post_id = (int) $post_id;
		if ( $post_id < 1 || ! newsai_breaking_liveblog_globally_enabled() ) {
			return false;
		}
		$hours = $hours === null ? newsai_breaking_default_hours() : (int) $hours;
		if ( ! in_array( $hours, [ 24, 48, 72 ], true ) ) {
			$hours = newsai_breaking_default_hours();
		}
		$now     = (int) current_time( 'timestamp' );
		$expires = $now + ( $hours * HOUR_IN_SECONDS );
		$keys    = newsai_breaking_meta_keys();

		update_post_meta( $post_id, $keys['active'], 'yes' );
		update_post_meta( $post_id, $keys['started'], $now );
		update_post_meta( $post_id, $keys['expires'], $expires );
		update_post_meta( $post_id, $keys['liveblog'], 'yes' );

		if ( function_exists( 'nros_clear_schema_cache_on_save' ) ) {
			nros_clear_schema_cache_on_save( $post_id );
		}

		newsai_breaking_ping_indexing( $post_id );
		do_action( 'newsai_breaking_activated', $post_id, $hours, $expires );
		return true;
	}
}

if ( ! function_exists( 'newsai_breaking_ping_indexing' ) ) {
	/**
	 * Immediate indexing ping (bypasses the short save_post debounce lock).
	 *
	 * @param int $post_id Post ID.
	 */
	function newsai_breaking_ping_indexing( $post_id ) {
		$post_id = (int) $post_id;
		$post    = get_post( $post_id );
		if ( ! $post || $post->post_status !== 'publish' ) {
			return;
		}
		if ( function_exists( 'newsai_is_pro' ) && ! newsai_is_pro() ) {
			return;
		}
		delete_transient( 'newsai_index_ping_lock_' . $post_id );

		if ( get_option( 'newsai_indexing_enabled', 'no' ) === 'yes' && function_exists( 'newsai_enqueue_indexing_ping' ) ) {
			newsai_enqueue_indexing_ping( $post_id );
		}
		if ( get_option( 'newsai_indexnow_enabled', 'no' ) === 'yes' && function_exists( 'newsai_indexnow_queue_submit' ) ) {
			newsai_indexnow_queue_submit( $post_id, true );
		}
	}
}

if ( ! function_exists( 'newsai_breaking_is_active' ) ) {
	/**
	 * @param int  $post_id Post ID.
	 * @param bool $check_expire Run lazy expire.
	 * @return bool
	 */
	function newsai_breaking_is_active( $post_id, $check_expire = true ) {
		$post_id = (int) $post_id;
		if ( $post_id < 1 ) {
			return false;
		}
		$keys = newsai_breaking_meta_keys();
		if ( get_post_meta( $post_id, $keys['active'], true ) !== 'yes' ) {
			return false;
		}
		if ( $check_expire ) {
			$expires = (int) get_post_meta( $post_id, $keys['expires'], true );
			if ( $expires > 0 && time() > $expires ) {
				newsai_breaking_deactivate( $post_id, true );
				return false;
			}
		}
		return true;
	}
}

if ( ! function_exists( 'newsai_breaking_is_legacy_liveblog_only' ) ) {
	/**
	 * Old posts that enabled LiveBlog before Breaking Mode existed.
	 */
	function newsai_breaking_is_legacy_liveblog_only( $post_id ) {
		$post_id = (int) $post_id;
		$keys    = newsai_breaking_meta_keys();
		if ( get_post_meta( $post_id, $keys['active'], true ) === 'yes' ) {
			return false;
		}
		return get_post_meta( $post_id, $keys['liveblog'], true ) === 'yes';
	}
}

if ( ! function_exists( 'newsai_breaking_ui_state' ) ) {
	/**
	 * @param int $post_id Post ID.
	 * @return array{active:bool,legacy:bool,started:int,expires:int,hours_left:float}
	 */
	function newsai_breaking_ui_state( $post_id ) {
		$post_id = (int) $post_id;
		$active  = newsai_breaking_is_active( $post_id );
		$legacy  = ! $active && newsai_breaking_is_legacy_liveblog_only( $post_id );
		$keys    = newsai_breaking_meta_keys();
		$started = (int) get_post_meta( $post_id, $keys['started'], true );
		$expires = (int) get_post_meta( $post_id, $keys['expires'], true );
		$left    = 0.0;
		if ( $active && $expires > time() ) {
			$left = ( $expires - time() ) / HOUR_IN_SECONDS;
		}
		return [
			'active'      => $active,
			'legacy'      => $legacy,
			'started'     => $started,
			'expires'     => $expires,
			'hours_left'  => round( $left, 1 ),
		];
	}
}

if ( ! function_exists( 'nros_is_valid_liveblog_heading' ) ) {
	/**
	 * Live update titles must be HH:MM — text (not readme == sections or plugin headers).
	 *
	 * @param string $headline Plain heading text.
	 * @return bool
	 */
	function nros_is_valid_liveblog_heading( $headline ) {
		$headline = trim( (string) $headline );
		if ( $headline === '' || mb_strlen( $headline, 'UTF-8' ) < 6 ) {
			return false;
		}
		if ( preg_match( '/={2,}/', $headline ) ) {
			return false;
		}
		$lower = mb_strtolower( $headline, 'UTF-8' );
		$needles = [
			'contributors:',
			'stable tag:',
			'requires at least',
			'tested up to',
			'license:',
			'== description',
			'== changelog',
		];
		foreach ( $needles as $needle ) {
			if ( strpos( $lower, $needle ) !== false ) {
				return false;
			}
		}
		$deny_exact = [ 'description', 'changelog', 'installation', 'screenshots', 'upgrade notice' ];
		if ( in_array( $lower, $deny_exact, true ) ) {
			return false;
		}
		return (bool) preg_match( '/\b([01]?\d|2[0-3])[:.]([0-5]\d)\s*(?:—|–|-)\s*\S/u', $headline );
	}
}

if ( ! function_exists( 'nros_count_liveblog_headings' ) ) {
	/**
	 * Count valid H3 live-update headings (matches liveBlogUpdate rules).
	 *
	 * @param string $content Post content.
	 * @return int
	 */
	function nros_count_liveblog_headings( $content ) {
		$content = (string) $content;
		if ( $content === '' ) {
			return 0;
		}
		$n = 0;
		if ( preg_match_all( '/<h3[^>]*>(.*?)<\/h3>/is', $content, $m ) && ! empty( $m[1] ) ) {
			foreach ( $m[1] as $raw ) {
				if ( nros_is_valid_liveblog_heading( wp_strip_all_tags( $raw ) ) ) {
					$n++;
				}
			}
		}
		return $n;
	}
}

if ( ! function_exists( 'nros_build_liveblog_article_body_plain' ) ) {
	/**
	 * Plain articleBody from valid H3 live sections only (skips pasted readme).
	 *
	 * @param string $content Post HTML content.
	 * @return string
	 */
	function nros_build_liveblog_article_body_plain( $content ) {
		$content = (string) $content;
		if ( $content === '' ) {
			return '';
		}
		$parts = [];
		if ( preg_match_all( '/<h3[^>]*>(.*?)<\/h3>(.*?)(?=<h[1-6]\b|$)/is', $content, $blocks, PREG_SET_ORDER ) ) {
			foreach ( $blocks as $block ) {
				$h = trim( wp_strip_all_tags( $block[1] ) );
				if ( ! nros_is_valid_liveblog_heading( $h ) ) {
					continue;
				}
				$body = trim( preg_replace( '/\s+/u', ' ', wp_strip_all_tags( $block[2] ) ) );
				$parts[] = $body !== '' ? $h . ': ' . $body : $h;
			}
		}
		return implode( "\n\n", $parts );
	}
}

if ( ! function_exists( 'nros_schema_text_looks_like_plugin_readme' ) ) {
	/**
	 * @param string $text Description or excerpt string.
	 * @return bool
	 */
	function nros_schema_text_looks_like_plugin_readme( $text ) {
		$text = trim( (string) $text );
		if ( $text === '' ) {
			return false;
		}
		if ( stripos( $text, 'Stable tag:' ) !== false ) {
			return true;
		}
		if ( stripos( $text, 'Requires at least:' ) !== false && stripos( $text, 'WordPress' ) !== false ) {
			return true;
		}
		if ( preg_match( '/^={2,}/m', $text ) ) {
			return true;
		}
		if ( stripos( $text, 'Turn WordPress into your newsroom command center' ) !== false ) {
			return true;
		}
		return false;
	}
}

if ( ! function_exists( 'nros_content_looks_like_readme' ) ) {
	/**
	 * Heuristic: plugin readme / changelog pasted into post body (avoid bogus liveBlogUpdate).
	 *
	 * @param string $content Post content.
	 * @return bool
	 */
	function nros_content_looks_like_readme( $content ) {
		$plain = wp_strip_all_tags( (string) $content );
		if ( strlen( $plain ) < 200 ) {
			return false;
		}
		$signals = 0;
		if ( stripos( $plain, 'Stable tag:' ) !== false ) {
			$signals++;
		}
		if ( stripos( $plain, 'Requires at least' ) !== false && stripos( $plain, 'WordPress' ) !== false ) {
			$signals++;
		}
		if ( preg_match( '/^={3,}\s/m', $plain ) ) {
			$signals++;
		}
		if ( stripos( $plain, 'Contributors:' ) !== false ) {
			$signals++;
		}
		return $signals >= 2;
	}
}

if ( ! function_exists( 'newsai_breaking_schedule_cron' ) ) {
	function newsai_breaking_schedule_cron() {
		if ( ! wp_next_scheduled( 'newsai_breaking_expire_scan' ) ) {
			wp_schedule_event( time() + 5 * MINUTE_IN_SECONDS, 'hourly', 'newsai_breaking_expire_scan' );
		}
	}
}
add_action( 'admin_init', 'newsai_breaking_schedule_cron' );

if ( ! function_exists( 'newsai_breaking_expire_scan' ) ) {
	function newsai_breaking_expire_scan() {
		$keys = newsai_breaking_meta_keys();
		$now  = time();
		$q    = new WP_Query(
			[
				'post_type'              => 'post',
				'post_status'            => 'publish',
				'posts_per_page'         => 40,
				'fields'                 => 'ids',
				'no_found_rows'          => true,
				'update_post_meta_cache' => false,
				'meta_query'             => [
					'relation' => 'AND',
					[
						'key'   => $keys['active'],
						'value' => 'yes',
					],
					[
						'key'     => $keys['expires'],
						'value'   => $now,
						'compare' => '<',
						'type'    => 'NUMERIC',
					],
				],
			]
		);
		if ( ! empty( $q->posts ) ) {
			foreach ( $q->posts as $pid ) {
				newsai_breaking_deactivate( (int) $pid, true );
			}
		}
	}
}
add_action( 'newsai_breaking_expire_scan', 'newsai_breaking_expire_scan' );

if ( ! function_exists( 'newsai_breaking_save_from_post' ) ) {
	/**
	 * Classic editor / metabox save (hidden + checkbox pattern).
	 */
	function newsai_breaking_save_from_post( $post_id ) {
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}
		if ( ! isset( $_POST['newsai_sidebar_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['newsai_sidebar_nonce'] ) ), 'newsai_sidebar_save' ) ) {
			return;
		}
		if ( ! newsai_breaking_liveblog_globally_enabled() ) {
			return;
		}
		if ( isset( $_POST['newsai_breaking_resolve'] ) && $_POST['newsai_breaking_resolve'] === '1' ) {
			newsai_breaking_deactivate( $post_id, false );
			return;
		}
		if ( newsai_breaking_is_active( $post_id, false ) && ! isset( $_POST['newsai_enable_breaking'] ) ) {
			return;
		}
		if ( ! isset( $_POST['newsai_enable_breaking'] ) ) {
			return;
		}
		$want = (string) wp_unslash( $_POST['newsai_enable_breaking'] );
		$on   = ( $want === '1' || $want === 'yes' );
		if ( $on ) {
			if ( ! newsai_breaking_is_active( $post_id, false ) ) {
				newsai_breaking_activate( $post_id );
			}
		} elseif ( newsai_breaking_is_active( $post_id, false ) || newsai_breaking_is_legacy_liveblog_only( $post_id ) ) {
			newsai_breaking_deactivate( $post_id, false );
		}
	}
}
add_action( 'save_post', 'newsai_breaking_save_from_post', 12 );

if ( ! function_exists( 'newsai_ajax_breaking_set' ) ) {
	function newsai_ajax_breaking_set() {
		newsai_editor_ajax_gate();
		$post_id = isset( $_POST['post_id'] ) ? (int) $_POST['post_id'] : 0;
		$enable  = isset( $_POST['enable'] ) && ( $_POST['enable'] === '1' || $_POST['enable'] === 'yes' );
		if ( $post_id < 1 ) {
			wp_send_json_error( [ 'message' => 'invalid_post' ], 400 );
		}
		newsai_editor_ajax_require_post_edit( $post_id );
		if ( ! newsai_breaking_liveblog_globally_enabled() ) {
			wp_send_json_error( [ 'message' => 'disabled' ], 400 );
		}
		if ( $enable ) {
			newsai_breaking_activate( $post_id );
		} else {
			newsai_breaking_deactivate( $post_id, false );
		}
		wp_send_json_success( [ 'state' => newsai_breaking_ui_state( $post_id ) ] );
	}
}
add_action( 'wp_ajax_newsai_breaking_set', 'newsai_ajax_breaking_set' );

if ( ! function_exists( 'newsai_ajax_breaking_resolve' ) ) {
	function newsai_ajax_breaking_resolve() {
		newsai_editor_ajax_gate();
		$post_id = isset( $_POST['post_id'] ) ? (int) $_POST['post_id'] : 0;
		if ( $post_id < 1 ) {
			wp_send_json_error( [ 'message' => 'invalid_post' ], 400 );
		}
		newsai_editor_ajax_require_post_edit( $post_id );
		newsai_breaking_deactivate( $post_id, false );
		wp_send_json_success( [ 'state' => newsai_breaking_ui_state( $post_id ) ] );
	}
}
add_action( 'wp_ajax_newsai_breaking_resolve', 'newsai_ajax_breaking_resolve' );

if ( ! function_exists( 'newsai_breaking_frontend_badge' ) ) {
	function newsai_breaking_frontend_badge( $content ) {
		if ( function_exists( 'newsai_lite_mode_skips_frontend_injections' ) && newsai_lite_mode_skips_frontend_injections() ) {
			return $content;
		}
		if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
			return $content;
		}
		if ( is_feed() || is_admin() ) {
			return $content;
		}
		if ( ! newsai_breaking_badge_enabled() || ! newsai_breaking_liveblog_globally_enabled() ) {
			return $content;
		}
		$post_id = (int) get_the_ID();
		if ( ! newsai_breaking_is_active( $post_id ) && ! newsai_breaking_is_legacy_liveblog_only( $post_id ) ) {
			return $content;
		}
		$label = __( 'DEVELOPING STORY', 'newsroom-ai-assistant' );
		$html  = '<p class="nros-breaking-badge" role="status" style="margin:0 0 16px;padding:10px 14px;background:#fef2f2;border-left:4px solid #dc2626;color:#991b1b;font-weight:700;font-size:13px;letter-spacing:0.03em;">'
			. esc_html( $label )
			. '</p>';
		$html = apply_filters( 'newsai_breaking_badge_html', $html, $post_id );
		return $html . $content;
	}
}
add_filter( 'the_content', 'newsai_breaking_frontend_badge', 3 );
