<?php
/** Redirects importer -> Redirection plugin. Idempotent: skips if the
 *  'Brentwood Migration' group already has items. */
if ( ! defined('ABSPATH') ) { exit; }
if ( ! class_exists('Red_Item') || ! class_exists('Red_Group') ) {
	// load plugin classes
	$base = WP_PLUGIN_DIR . '/redirection/redirection.php';
	if ( file_exists($base) ) { include_once $base; }
}
if ( ! class_exists('Red_Item') ) { echo "Redirection plugin classes not available\n"; return; }

$GROUP = 'Brentwood Migration';

// find or create group (module_id 1 = WordPress)
$gid = 0;
foreach ( Red_Group::get_all() as $g ) { if ( $g['name'] === $GROUP ) { $gid = $g['id']; break; } }
if ( ! $gid ) {
	$grp = Red_Group::create( $GROUP, 1 );
	$gid = is_object($grp) ? $grp->get_id() : ( is_array($grp) ? $grp['id'] : 0 );
}
if ( ! $gid ) { echo "could not create group\n"; return; }

// guard against double import
global $wpdb;
$have = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}redirection_items WHERE group_id=%d", $gid ) );
if ( $have > 0 ) { echo "Group #$gid already has $have redirects — skipping.\n"; return; }

$rows = json_decode( file_get_contents( WP_CONTENT_DIR . '/_import/redirects.json' ), true );
$ok=0; $fail=0; $disabled=0;
foreach ( $rows as $r ) {
	$details = array(
		'url'         => $r['url'],
		'regex'       => $r['regex'] ? 1 : 0,
		'match_type'  => 'url',
		'action_type' => 'url',
		'action_code' => 301,
		'action_data' => array( 'url' => $r['target'] ),
		'group_id'    => $gid,
		'title'       => $r['title'],
		'position'    => $r['position'],
	);
	if ( $r['status'] === 'disabled' ) { $details['status'] = 'disabled'; }
	$res = Red_Item::create( $details );
	if ( is_wp_error($res) ) { $fail++; }
	else { $ok++; if ( $r['status']==='disabled' ) { $disabled++; } }
}
echo "REDIRECTS: group=$gid created=$ok (disabled/needs-target=$disabled) failed=$fail\n";
