<?php
/**
 * Kantan Analytics — Site / Business Profile.
 *
 * The canonical, human-owned source of business truth (hours, offerings, NAP,
 * brand voice, claims) that the downloadable Kantan agents read BEFORE generating
 * or rewriting content. Stored as Markdown in a wp_option, served over the REST
 * API; the agents fetch it live on every content task via a "ground truth"
 * directive baked into their instructions.
 *
 * Lives in Analytics (the base plugin) so both the Analytics and SEO agents read
 * one source via GET /kantan/v1/profile.
 *
 * @since 2.18.0
 */

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

/** Starter skeleton (Markdown) shown in the editor before the profile is filled. */
function kantan_site_profile_default() {
    $name = get_bloginfo('name');
    $url  = home_url('/');
    return "# Business Profile — {$name}\n\n"
        . "> Canonical facts the Kantan agents treat as GROUND TRUTH when writing or rewriting content. Keep this accurate — agents read it before generating anything, and won't invent facts that live here.\n\n"
        . "## Business basics\n"
        . "- **Name:** {$name}\n"
        . "- **Website:** {$url}\n"
        . "- **What we do (1–2 sentences):** \n"
        . "- **Service area / locations:** \n"
        . "- **Address (NAP — keep exact for local SEO):** \n"
        . "- **Phone:** \n"
        . "- **Hours:** \n\n"
        . "## Offerings\n"
        . "- List your products / services / plans — names, one-line descriptions, and public prices.\n\n"
        . "## Audience\n"
        . "- Who you serve; the primary customer and what they care about.\n\n"
        . "## Brand voice & tone\n"
        . "- e.g. friendly-expert, plain language, no hype. Words/phrases to use — and ones to avoid.\n\n"
        . "## Claims & compliance\n"
        . "- **Safe to claim:** \n"
        . "- **Never claim / must avoid:** \n\n"
        . "## Key pages & primary CTAs\n"
        . "- Your most important pages and the action each should drive.\n\n"
        . "## Target topics & search intent\n"
        . "- Core topics/keywords; the buying-intent terms that matter most.\n\n"
        . "## Competitors & differentiation\n"
        . "- Main competitors, and how you're genuinely different.\n\n"
        . "## Anything else the agent should know\n"
        . "- \n";
}

/** The stored profile Markdown, or '' if never set. */
function kantan_site_profile_get() {
    return (string) get_option('kantan_site_profile', '');
}

/** Whether a meaningful profile has been saved. */
function kantan_site_profile_is_set() {
    return trim(kantan_site_profile_get()) !== '';
}

add_action('rest_api_init', function () {
    register_rest_route('kantan/v1', '/profile', array(
        array('methods' => 'GET',  'callback' => 'kantan_site_profile_rest_get',  'permission_callback' => 'kantan_rest_permission'),
        array('methods' => 'PUT',  'callback' => 'kantan_site_profile_rest_save', 'permission_callback' => 'kantan_rest_permission'),
    ));
});

/**
 * GET /kantan/v1/profile — the agent reads this before content work.
 * `content` is the live truth ('' if unset); `default` is the editor skeleton.
 */
function kantan_site_profile_rest_get() {
    $content = kantan_site_profile_get();
    return rest_ensure_response(array(
        'content'    => $content,
        'is_set'     => trim($content) !== '',
        'updated_at' => (string) get_option('kantan_site_profile_updated', ''),
        'default'    => $content === '' ? kantan_site_profile_default() : null,
    ));
}

/**
 * PUT /kantan/v1/profile — save the canonical profile. Used by the dashboard
 * editor (human) and, with the user's approval, by an agent drafting it.
 */
function kantan_site_profile_rest_save($request) {
    $body = $request->get_json_params();
    if (!is_array($body) || !isset($body['content'])) {
        return new WP_Error('missing_content', 'No profile content provided.', array('status' => 400));
    }
    // Markdown is plain text — strip any HTML, keep line breaks, cap length.
    $content = sanitize_textarea_field((string) $body['content']);
    if (strlen($content) > 20000) {
        $content = substr($content, 0, 20000);
    }
    update_option('kantan_site_profile', $content);
    update_option('kantan_site_profile_updated', current_time('mysql'));

    return rest_ensure_response(array(
        'saved'      => true,
        'content'    => $content,
        'is_set'     => trim($content) !== '',
        'updated_at' => (string) get_option('kantan_site_profile_updated', ''),
    ));
}
