<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Forme_SEO_API {

	private string $base_url;
	private string $api_key;

	public function __construct( string $base_url = '', string $api_key = '' ) {
		$this->base_url = rtrim(
			$base_url ?: (string) get_option( FORME_SEO_OPT_API_BASE, FORME_SEO_DEFAULT_API ),
			'/'
		);
		$this->api_key = $api_key ?: (string) get_option( FORME_SEO_OPT_API_KEY, '' );
	}

	// ── Public endpoints ──────────────────────────────────────────────────────

	public function register( string $email, string $site_url ): array {
		return $this->post( 'api/register', compact( 'email', 'site_url' ), false );
	}

	public function health(): array {
		return $this->get( 'health' );
	}

	public function me(): array {
		return $this->get( 'api/me' );
	}

	public function usage(): array {
		return $this->get( 'api/usage' );
	}

	public function create_checkout_session( string $plan ): array {
		return $this->post( 'billing/create-checkout-session', [
			'plan'        => $plan,
			'success_url' => admin_url( 'admin.php?page=claude-seo-agent&billing=success' ),
			'cancel_url'  => admin_url( 'admin.php?page=claude-seo-agent&billing=cancel' ),
		] );
	}

	public function create_portal_session(): array {
		return $this->post( 'billing/create-portal-session', [
			'return_url' => admin_url( 'admin.php?page=claude-seo-agent' ),
		] );
	}

	// ── SEO tools ─────────────────────────────────────────────────────────────

	public function audit( string $url ): array {
		return $this->post( 'api/audit', compact( 'url' ) );
	}

	public function technical( string $url ): array {
		return $this->post( 'api/technical', compact( 'url' ) );
	}

	public function content( string $url ): array {
		return $this->post( 'api/content', compact( 'url' ) );
	}

	public function schema( string $url ): array {
		return $this->post( 'api/schema', compact( 'url' ) );
	}

	public function sitemap( string $url ): array {
		return $this->post( 'api/sitemap', compact( 'url' ) );
	}

	public function images( string $url ): array {
		return $this->post( 'api/images', compact( 'url' ) );
	}

	public function content_pillars( string $type = '' ): array {
		return $this->post( 'api/content-pillars', [
			'type' => $type,
		] );
	}

	public function poll_job( string $job_id ): array {
		return $this->get( 'api/jobs/' . rawurlencode( $job_id ) );
	}

	public function list_jobs( string $category = '', string $tool = '', int $limit = 20, int $offset = 0 ): array {
		$qs = http_build_query( array_filter( [
			'category' => $category,
			'tool'     => $tool,
			'limit'    => $limit,
			'offset'   => $offset,
		] ) );
		return $this->get( 'api/jobs' . ( $qs ? "?{$qs}" : '' ) );
	}

	// ── Reports ───────────────────────────────────────────────────────────────

	public function get_reports( string $tool = '', int $limit = 20, int $offset = 0 ): array {
		$qs = http_build_query( array_filter( [ 'tool' => $tool, 'limit' => $limit, 'offset' => $offset ] ) );
		return $this->get( 'api/reports' . ( $qs ? "?{$qs}" : '' ) );
	}

	public function get_report( string $report_id ): array {
		return $this->get( 'api/reports/' . rawurlencode( $report_id ) );
	}

	// ── Tasks ─────────────────────────────────────────────────────────────────

	public function get_tasks( string $status = '', string $priority = '', string $category = '', int $limit = 50 ): array {
		$qs = http_build_query( array_filter( [
			'status'   => $status,
			'priority' => $priority,
			'category' => $category,
			'limit'    => $limit,
		] ) );
		return $this->get( 'api/tasks' . ( $qs ? "?{$qs}" : '' ) );
	}

	public function get_quick_wins( int $limit = 5 ): array {
		return $this->get( "api/tasks/quick-wins?limit={$limit}" );
	}

	public function update_task( int $task_id, string $status ): array {
		return $this->patch( "api/tasks/{$task_id}", [ 'status' => $status ] );
	}

	// ── Content projects ──────────────────────────────────────────────────────

	public function get_content_projects(): array {
		return $this->get( 'api/content-projects' );
	}

	public function get_content_project( string $project_id ): array {
		return $this->get( 'api/content-projects/' . rawurlencode( $project_id ) );
	}

	public function generate_outline( string $project_id, string $topic_id ): array {
		return $this->post( "api/content-projects/{$project_id}/topics/{$topic_id}/outline", [] );
	}

	public function generate_article( string $project_id, string $topic_id ): array {
		return $this->post( "api/content-projects/{$project_id}/topics/{$topic_id}/write", [] );
	}

	public function site_profile(): array {
		return $this->get( 'api/site-profile' );
	}

	public function get_content_topics( string $status = '', int $limit = 50 ): array {
		$qs = http_build_query( array_filter( [ 'status' => $status, 'limit' => $limit ] ) );
		return $this->get( 'api/content-topics' . ( $qs ? "?{$qs}" : '' ) );
	}

	public function blog_strategy( $payload ): array {

		if ( is_string( $payload ) ) {
			$payload = [
				'niche' => $payload,
			];
		}

		return $this->post(
			'api/blog-strategy',
			$payload
		);
	}

	public function blog_write( string $topic ): array {
		return $this->post( 'api/blog-write', [
			'topic' => $topic,
		] );
	}

	public function blog_write_async( string $topic ): array {
		$response = wp_remote_post(
			$this->base_url . '/api/blog-write',
			[
				'headers'  => $this->headers(),
				'body'     => wp_json_encode( [ 'topic' => $topic ] ),
				'timeout'  => 1,
				'blocking' => false,
			]
		);

		if ( is_wp_error( $response ) ) {
			return [ 'success' => false, 'message' => $response->get_error_message(), 'code' => 0 ];
		}

		return [
			'success' => true,
			'data'    => [
				'status' => 'queued',
				'topic'  => $topic,
			],
		];
	}

	public function blog_calendar( array $payload ): array {
		return $this->post( 'api/blog-calendar', $payload );
	}
	// ── GSC ────────────────────────────────────────────────────────────────────

	public function gsc_auth_url( string $return_url = '' ): array {
		return $this->get( 'api/gsc/auth-url' . ( $return_url ? '?' . http_build_query( [ 'return_url' => $return_url ] ) : '' ) );
	}

	public function gsc_properties(): array {
		return $this->get( 'api/gsc/properties' );
	}

	public function gsc_select_property( string $property ): array {
		return $this->post( 'api/gsc/select-property', [ 'property' => $property ] );
	}

	public function gsc_overview(): array {
		// Pass a rolling 28-day window with a 3-day lag to avoid GSC data delays
		// at month boundaries (GSC data is typically 2-3 days behind).
		$end   = ( new \DateTime( 'now', new \DateTimeZone( 'UTC' ) ) )
		           ->modify( '-3 days' )
		           ->format( 'Y-m-d' );
		$start = ( new \DateTime( $end, new \DateTimeZone( 'UTC' ) ) )
		           ->modify( '-27 days' )
		           ->format( 'Y-m-d' );

		return $this->get( 'api/gsc/overview', [
			'start_date' => $start,
			'end_date'   => $end,
		] );
	}

	public function gsc_disconnect(): array {
		$response = wp_remote_request(
			$this->base_url . '/api/gsc/disconnect',
			[
				'method'  => 'DELETE',
				'headers' => $this->headers(),
				'timeout' => 15,
			]
		);
		return $this->parse( $response );
	}

	// ── Internals ─────────────────────────────────────────────────────────────

	private function headers( bool $auth = true ): array {
		$h = [
			'Content-Type' => 'application/json',
			'Accept'       => 'application/json',
		];
		if ( $auth && $this->api_key ) {
			$h['X-API-Key'] = $this->api_key;
		}
		return $h;
	}

	private function get( string $endpoint, array $params = [] ): array {
		$url = $this->base_url . '/' . $endpoint;
		if ( ! empty( $params ) ) {
			$url = add_query_arg( array_map( 'rawurlencode', $params ), $url );
		}
		$response = wp_remote_get(
			$url,
			[ 'headers' => $this->headers(), 'timeout' => 600 ]
		);
		return $this->parse( $response );
	}

	private function post( string $endpoint, array $body, bool $auth = true ): array {
		$response = wp_remote_post(
			$this->base_url . '/' . $endpoint,
			[
				'headers' => $this->headers( $auth ),
				'body'    => wp_json_encode( $body ),
				'timeout' => 600,
			]
		);
		return $this->parse( $response );
	}

	private function patch( string $endpoint, array $body ): array {
		$response = wp_remote_request(
			$this->base_url . '/' . $endpoint,
			[
				'method'  => 'PATCH',
				'headers' => $this->headers(),
				'body'    => wp_json_encode( $body ),
				'timeout' => 600,
			]
		);
		return $this->parse( $response );
	}

	private function parse( $response ): array {
		if ( is_wp_error( $response ) ) {
			return [ 'success' => false, 'message' => $response->get_error_message(), 'code' => 0 ];
		}

		$code = (int) wp_remote_retrieve_response_code( $response );
		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true ) ?: [];

		if ( 401 === $code ) {
			return [ 'success' => false, 'message' => 'Unauthorized — check your API key.', 'code' => 401 ];
		}

		// For error responses, merge the body so job_id / reset_hint are never lost.
		if ( $code >= 400 ) {
			$msg = $data['detail'] ?? $data['error'] ?? $data['message']
				?? ( 429 === $code ? 'Rate limit — please wait and try again.' : "Server error ({$code})." );
			return array_merge( [ 'success' => false, 'message' => $msg, 'code' => $code ], $data );
		}

		return [ 'success' => true, 'data' => $data, 'code' => $code ];
	}

	
}
