<?php
/**
 * Importeur d'articles de blog Covalba (wp eval-file).
 * Lit un JSON (CVB_IMPORT_JSON ou /tmp/blog-import.json) et upsert des posts :
 * post_content (HTML éditeur classique), ACF article.en_bref / article.bibliographie,
 * SEO (titre_seo / meta_description / canonical), catégorie, auteur, image à la une.
 * Idempotent : retrouve le post par slug (post_name) et le met à jour.
 */

if (!defined('ABSPATH')) { fwrite(STDERR, "Run via wp eval-file\n"); exit(1); }

$path = getenv('CVB_IMPORT_JSON') ?: '/tmp/blog-import.json';
$items = json_decode(file_get_contents($path), true);
if (!is_array($items)) { WP_CLI::error("JSON illisible: $path"); }

require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';

// --- auteur Maxime Bourassin ---
$author = get_user_by('login', 'maxime');
if (!$author) {
    $uid = wp_insert_user([
        'user_login'   => 'maxime',
        'user_pass'    => wp_generate_password(24),
        'display_name' => 'Maxime Bourassin',
        'first_name'   => 'Maxime',
        'last_name'    => 'Bourassin',
        'role'         => 'author',
    ]);
    $author_id = is_wp_error($uid) ? 1 : $uid;
} else {
    $author_id = $author->ID;
}

// --- catégories ---
function cvb_term_id(string $name): int {
    $t = get_term_by('name', $name, 'category');
    if ($t) return (int) $t->term_id;
    $r = wp_insert_term($name, 'category');
    return is_wp_error($r) ? 0 : (int) $r['term_id'];
}

// --- image à la une : résoudre dans la médiathèque, sinon télécharger ---
function cvb_set_hero(int $post_id, string $url, string $alt): string {
    if (!$url) return 'none';
    $aid = attachment_url_to_postid($url);
    $how = 'resolved';
    if (!$aid) {
        // og:image covalba.fr déjà migrée → tenter le basename minuscule sous uploads
        $base = strtolower(basename(parse_url($url, PHP_URL_PATH)));
        $guess = 'https://covalba-admin.paf-studio.dev/wp-content/uploads/2026/06/' . $base;
        $aid = attachment_url_to_postid($guess);
        if ($aid) $how = 'resolved-basename';
    }
    if (!$aid) {
        $aid = media_sideload_image($url, $post_id, $alt, 'id');
        if (is_wp_error($aid) || !$aid) return 'FAILED:' . (is_wp_error($aid) ? $aid->get_error_message() : '0');
        $how = 'sideloaded';
    }
    update_post_meta($aid, '_wp_attachment_image_alt', $alt);
    set_post_thumbnail($post_id, $aid);
    return $how;
}

$created = 0; $updated = 0; $heroStats = [];
foreach ($items as $a) {
    $slug = $a['slug'];
    if (!$slug) continue;

    $existing = get_page_by_path($slug, OBJECT, 'post');
    $postdate_gmt = gmdate('Y-m-d H:i:s', strtotime($a['date'] ?? 'now'));
    $postdate     = get_date_from_gmt($postdate_gmt);

    $data = [
        'post_type'     => 'post',
        'post_status'   => 'publish',
        'post_name'     => $slug,
        'post_title'    => $a['title'],
        'post_content'  => $a['bodyHtml'],
        'post_excerpt'  => $a['metaDescription'] ?? '',
        'post_author'   => $author_id,
        'post_date'     => $postdate,
        'post_date_gmt' => $postdate_gmt,
    ];
    if ($existing) { $data['ID'] = $existing->ID; $pid = wp_update_post($data, true); $updated++; }
    else { $pid = wp_insert_post($data, true); $created++; }
    if (is_wp_error($pid)) { WP_CLI::warning("[$slug] " . $pid->get_error_message()); continue; }
    if (function_exists('pll_set_post_language')) pll_set_post_language((int) $pid, 'fr');

    // catégorie
    $term = cvb_term_id($a['category'] ?? 'Cool roof');
    if ($term) wp_set_object_terms($pid, [$term], 'category', false);

    // ACF : En bref + Bibliographie (par clés de champ)
    $enbref = array_map(fn($p) => ['point' => $p], $a['enBref'] ?? []);
    $biblio = array_map(fn($s) => ['reference' => $s['reference'] ?? '', 'url' => $s['url'] ?? ''], $a['sources'] ?? []);
    update_field('field_cvb_article_en_bref', $enbref, $pid);
    update_field('field_cvb_article_bibliographie', $biblio, $pid);

    // SEO
    update_field('field_cvb_seo_titre_seo', $a['titleSeo'] ?? '', $pid);
    update_field('field_cvb_seo_meta_description', $a['metaDescription'] ?? '', $pid);
    update_field('field_cvb_seo_canonical', 'https://www.covalba.fr/blog/' . $slug, $pid);

    // image à la une
    $how = cvb_set_hero($pid, $a['hero'] ?? '', $a['title']);
    $heroStats[$how] = ($heroStats[$how] ?? 0) + 1;
}

WP_CLI::success("Articles — créés: $created, mis à jour: $updated");
WP_CLI::log('Hero: ' . json_encode($heroStats, JSON_UNESCAPED_UNICODE));
WP_CLI::log('Total posts (post): ' . wp_count_posts('post')->publish);
