<?php
/**
 * Internal Link Health Module.
 *
 * Surfaces the internal-link health of the site: total internal links, orphan
 * pages (no inbound internal links), and broken internal links. Adds a report
 * page under Helm → Link Health, and feeds the Command Center dashboard cards
 * with real numbers via the `platform_helm_dashboard_metrics` filter.
 *
 * @package Platform\Helm\Modules\Link_Health
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\Link_Health;

use Platform\Helm\Contracts\ModuleInterface;

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

final class LinkHealthModule implements ModuleInterface {

	private HealthAnalyzer $analyzer;
	private HealthPage $page;
	private PostLinkMetaBox $meta_box;
	private HealthAlerts $alerts;

	public function __construct() {
		$this->analyzer = new HealthAnalyzer();
		$this->page     = new HealthPage( $this->analyzer );
		$this->meta_box = new PostLinkMetaBox( $this->analyzer );
		$this->alerts   = new HealthAlerts( $this->analyzer );
	}

	public function id(): string {
		return 'link_health';
	}

	public function name(): string {
		return __( 'Internal Link Health', 'platform-helm' );
	}

	public function description(): string {
		return __( 'A health report for your internal linking: orphan pages with no inbound links, total internal links, and broken internal links. Adds a report page, a per-post Link Summary meta box in the editor, and feeds the Command Center stats.', 'platform-helm' );
	}

	public function default_enabled(): bool {
		return true;
	}

	public function boot(): void {
		$this->page->register_hooks();
		$this->meta_box->register_hooks();
		$this->alerts->register_hooks();
		add_filter( 'platform_helm_dashboard_metrics', [ $this, 'supply_metrics' ] );
	}

	/**
	 * Provide real numbers for the dashboard cards. Reads the cached report so
	 * the dashboard never triggers a fresh scan on load.
	 *
	 * @param array<string,mixed> $metrics
	 * @return array<string,mixed>
	 */
	public function supply_metrics( array $metrics ): array {
		$report = $this->analyzer->get_report();
		$metrics['orphan_count'] = (int) ( $report['orphan_count'] ?? 0 );
		$metrics['total_links']  = (int) ( $report['total_links'] ?? 0 );
		$metrics['broken_links'] = (int) ( $report['broken_count'] ?? 0 );
		return $metrics;
	}
}
