<?php
/**
 * Traffic analysis module bootstrap.
 *
 * @package Niwa_AI
 */

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

class Niwa_AI_Traffic_Module {

	private Niwa_AI_Traffic_Repository $repository;
	private Niwa_AI_Traffic_REST_Controller $rest_controller;
	private Niwa_AI_Traffic_Conversion_Tracker $conversion_tracker;
	private Niwa_AI_Traffic_Rollup_Worker $rollup_worker;
	private Niwa_AI_Traffic_Dashboard_Widget $dashboard_widget;

	public function __construct() {
		$this->repository         = new Niwa_AI_Traffic_Repository();
		$this->rest_controller    = new Niwa_AI_Traffic_REST_Controller( $this->repository );
		$this->conversion_tracker = new Niwa_AI_Traffic_Conversion_Tracker( $this->repository );
		$this->rollup_worker      = new Niwa_AI_Traffic_Rollup_Worker();
		$this->dashboard_widget   = new Niwa_AI_Traffic_Dashboard_Widget( $this->repository );
	}

	public function register_hooks(): void {
		$this->rest_controller->register_hooks();
		$this->conversion_tracker->register_hooks();
		$this->rollup_worker->register_hooks();
		$this->dashboard_widget->register_hooks();
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_collector' ), 15 );
		add_action( 'init', array( $this, 'maybe_schedule_events' ), 20 );
	}

	public function get_repository(): Niwa_AI_Traffic_Repository {
		return $this->repository;
	}

	public static function activate(): void {
		Niwa_AI_Traffic_DB::ensure_schema( true );
		Niwa_AI_Traffic_Rollup_Worker::schedule();
	}

	public function maybe_schedule_events(): void {
		if ( is_admin() || wp_doing_cron() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
			Niwa_AI_Traffic_Rollup_Worker::schedule();
		}
	}

	public function enqueue_collector(): void {
		if ( is_admin() || wp_doing_ajax() || wp_doing_cron() || ! apply_filters( 'niwa_ai_traffic_collection_enabled', true ) ) {
			return;
		}

		Niwa_AI_Session_Utils::resolve_verified_session( true );

		$dist_rel = 'assets/dist/traffic-collector.min.js';
		$src_rel  = 'assets/js/traffic-collector.js';
		$rel_path = file_exists( NIWA_AI_DIR . $dist_rel ) ? $dist_rel : $src_rel;

		wp_enqueue_script(
			'niwa-ai-traffic-collector',
			NIWA_AI_URL . $rel_path,
			array(),
			self::asset_version( $rel_path ),
			true
		);

		wp_localize_script(
			'niwa-ai-traffic-collector',
			'NiwaTraffic',
			array(
				'enabled'    => true,
				'endpoint'   => esc_url_raw( rest_url( Niwa_AI_Traffic_REST_Controller::REST_NAMESPACE . Niwa_AI_Traffic_REST_Controller::REST_ROUTE ) ),
				'siteHost'   => wp_parse_url( home_url( '/' ), PHP_URL_HOST ),
				'sessionTtl' => 30 * MINUTE_IN_SECONDS,
				'batchSize'  => 8,
			)
		);
	}

	private static function asset_version( $rel_path ): string {
		$file = NIWA_AI_DIR . ltrim( (string) $rel_path, '/' );
		if ( file_exists( $file ) ) {
			return NIWA_AI_VERSION . '.' . filemtime( $file );
		}
		return NIWA_AI_VERSION;
	}
}
