<?php
require_once dirname(__DIR__) . '/bootstrap.php';

use CAE\Lib\Response;
use CAE\Lib\Database;
use CAE\Models\Project;
use CAE\Models\Topic;
use CAE\Models\PageType;
use CAE\Models\PromptTemplate;
use CAE\Modules\ContentEngine\ContentGenerator;
use CAE\Modules\ContentEngine\ContentExtras;
use CAE\Modules\ExportEngine\ExportEngine;

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$uri    = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$base   = rtrim(str_replace('index.php', '', $_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
$path   = '/' . trim(substr($uri, strlen($base)), '/');

// Support PUT/DELETE via _method
if ($method === 'POST') {
    $body = json_decode(file_get_contents('php://input'), true) ?? [];
    if (!empty($body['_method'])) {
        $method = strtoupper($body['_method']);
    }
} else {
    $body = [];
}

// Input helper
$input = function(string $key, mixed $default = null) use ($body): mixed {
    return $body[$key] ?? $_POST[$key] ?? $_GET[$key] ?? $default;
};

// Route matcher
$match = function(string $pattern, string $uri): array|false {
    $regex = '#^' . preg_replace('/\{(\w+)\}/', '(?P<$1>[^/]+)', $pattern) . '$#';
    return preg_match($regex, $uri, $m) ? array_filter($m, 'is_string', ARRAY_FILTER_USE_KEY) : false;
};

try {
    // =========================================================
    // PROJECTS
    // =========================================================
    if ($method === 'GET' && $path === '/api/projects') {
        $proj = new Project();
        Response::success($proj->all());
    }
    elseif ($method === 'GET' && ($m = $match('/api/projects/{id}', $path))) {
        $proj = (new Project())->find((int)$m['id']);
        $proj ? Response::success($proj) : Response::error('Project not found', 404);
    }
    elseif ($method === 'POST' && $path === '/api/projects') {
        $required = ['business_name'];
        foreach ($required as $f) {
            if (empty($input($f))) Response::error("Field '{$f}' is required");
        }
        $id = (new Project())->create([
            'business_name'         => $input('business_name'),
            'website_url'           => $input('website_url'),
            'target_audience'       => $input('target_audience'),
            'content_intent'        => $input('content_intent'),
            'brand_positioning'     => $input('brand_positioning'),
            'tone_voice'            => $input('tone_voice', 'professional'),
            'brand_dos'             => $input('brand_dos'),
            'brand_donts'           => $input('brand_donts'),
            'pov_type'              => $input('pov_type', 'third_person'),
            'seo_philosophy'        => $input('seo_philosophy'),
            'compliance_rules'      => $input('compliance_rules'),
            'cta_style'             => $input('cta_style'),
            'no_no_words'           => $input('no_no_words'),
            'guideline_doc_url'     => $input('guideline_doc_url'),
        ]);
        Response::success(['id' => $id], 'Project created', 201);
    }
    elseif ($method === 'PUT' && ($m = $match('/api/projects/{id}', $path))) {
        (new Project())->update((int)$m['id'], array_filter($body, fn($v) => $v !== null));
        Response::success(null, 'Project updated');
    }
    elseif ($method === 'DELETE' && ($m = $match('/api/projects/{id}', $path))) {
        (new Project())->delete((int)$m['id']);
        Response::success(null, 'Project deleted');
    }

    // =========================================================
    // TOPICS
    // =========================================================
    elseif ($method === 'GET' && $path === '/api/topics') {
        $projectId = (int)($input('project_id') ?? 0);
        $status    = $input('status');
        if (!$projectId) Response::error('project_id required');
        Response::success((new Topic())->allByProject($projectId, $status ?: null));
    }
    elseif ($method === 'GET' && ($m = $match('/api/topics/{id}', $path))) {
        $t = (new Topic())->find((int)$m['id']);
        $t ? Response::success($t) : Response::error('Topic not found', 404);
    }
    elseif ($method === 'POST' && $path === '/api/topics') {
        foreach (['project_id', 'title', 'primary_keyword', 'page_type_id'] as $f) {
            if (empty($input($f))) Response::error("Field '{$f}' is required");
        }
        $id = (new Topic())->create([
            'project_id'          => (int)$input('project_id'),
            'page_type_id'        => (int)$input('page_type_id'),
            'title'               => $input('title'),
            'primary_keyword'     => $input('primary_keyword'),
            'supporting_keywords' => $input('supporting_keywords'),
            'search_intent'       => $input('search_intent', 'informational'),
            'content_angle'       => $input('content_angle'),
            'target_word_count'   => (int)($input('target_word_count') ?? 1200),
            'status'              => 'pending',
        ]);
        Response::success(['id' => $id], 'Topic created', 201);
    }
    elseif ($method === 'PUT' && ($m = $match('/api/topics/{id}', $path))) {
        (new Topic())->update((int)$m['id'], array_filter($body, fn($v) => $v !== null));
        Response::success(null, 'Topic updated');
    }
    elseif ($method === 'DELETE' && ($m = $match('/api/topics/{id}', $path))) {
        (new Topic())->delete((int)$m['id']);
        Response::success(null, 'Topic deleted');
    }

    // =========================================================
    // CONTENT GENERATION
    // =========================================================
    elseif ($method === 'POST' && $path === '/api/content/generate') {
        $topicIds = $input('topic_ids', []);
        if (empty($topicIds) || !is_array($topicIds)) {
            Response::error('topic_ids array required');
        }
        set_time_limit(600); // allow up to 10 min for large batches with retries
        $generator = new ContentGenerator();
        $results   = $generator->generateBatch(array_map('intval', $topicIds));
        Response::success($results, 'Generation complete');
    }
    elseif ($method === 'GET' && $path === '/api/content') {
        $db   = Database::getInstance();
        $rows = $db->fetchAll(
            "SELECT gc.id, gc.status, gc.input_tokens, gc.output_tokens, gc.model_used,
                    gc.generation_time_ms, gc.created_at,
                    t.title, t.primary_keyword, p.business_name, pt.name AS page_type_name,
                    q.word_count, q.passed AS qa_passed
             FROM generated_content gc
             LEFT JOIN topics t      ON t.id  = gc.topic_id
             LEFT JOIN projects p    ON p.id  = t.project_id
             LEFT JOIN page_types pt ON pt.id = t.page_type_id
             LEFT JOIN qa_logs q     ON q.content_id = gc.id
             ORDER BY gc.created_at DESC
             LIMIT 100"
        );
        Response::success($rows);
    }
    elseif ($method === 'GET' && ($m = $match('/api/content/{id}', $path))) {
        $db  = Database::getInstance();
        $row = $db->fetch(
            "SELECT gc.*, t.title, t.primary_keyword, p.business_name, pt.name AS page_type_name,
                    q.word_count, q.passed AS qa_passed, q.issues_found, q.keyword_density
             FROM generated_content gc
             LEFT JOIN topics t   ON t.id  = gc.topic_id
             LEFT JOIN projects p ON p.id  = t.project_id
             LEFT JOIN page_types pt ON pt.id = t.page_type_id
             LEFT JOIN qa_logs q  ON q.content_id = gc.id
             WHERE gc.id = ?
             LIMIT 1",
            [(int)$m['id']]
        );
        $row ? Response::success($row) : Response::error('Content not found', 404);
    }
    elseif ($method === 'POST' && ($m = $match('/api/content/{id}/approve', $path))) {
        $db = Database::getInstance();
        $db->update('generated_content', ['status' => 'approved', 'updated_at' => date('Y-m-d H:i:s')], 'id = :id', ['id' => (int)$m['id']]);
        $db->update('topics', ['status' => 'approved', 'updated_at' => date('Y-m-d H:i:s')], 'id = (SELECT topic_id FROM generated_content WHERE id = :id)', ['id' => (int)$m['id']]);
        Response::success(null, 'Content approved');
    }
    elseif ($method === 'DELETE' && ($m = $match('/api/content/{id}', $path))) {
        Database::getInstance()->delete('generated_content', 'id = ?', [(int)$m['id']]);
        Response::success(null, 'Content deleted');
    }

    // =========================================================
    // CONTENT EXTRAS (meta tags, schema, anchor text, images, internal links)
    // =========================================================
    elseif ($method === 'POST' && ($m = $match('/api/content/{id}/extras/meta-tags', $path))) {
        $result = (new ContentExtras())->generateMetaTags((int)$m['id']);
        Response::success($result, 'Meta tags generated');
    }
    elseif ($method === 'POST' && ($m = $match('/api/content/{id}/extras/schema', $path))) {
        $result = (new ContentExtras())->generateSchema((int)$m['id']);
        Response::success(['schema' => $result], 'Schema generated');
    }
    elseif ($method === 'POST' && ($m = $match('/api/content/{id}/extras/anchor-text', $path))) {
        $result = (new ContentExtras())->generateAnchorText((int)$m['id']);
        Response::success($result, 'Anchor text generated');
    }
    elseif ($method === 'POST' && ($m = $match('/api/content/{id}/extras/images', $path))) {
        $result = (new ContentExtras())->generateImageSuggestions((int)$m['id']);
        Response::success($result, 'Image suggestions generated');
    }
    elseif ($method === 'GET' && ($m = $match('/api/content/{id}/extras/internal-links', $path))) {
        $result = (new ContentExtras())->getInternalLinks((int)$m['id']);
        Response::success($result);
    }
    elseif ($method === 'POST' && ($m = $match('/api/content/{id}/ai-fix', $path))) {
        $instruction = trim($body['instruction'] ?? '');
        if (empty($instruction)) Response::error('instruction is required');
        set_time_limit(120);
        $result = (new ContentExtras())->aiFix((int)$m['id'], $instruction);
        Response::success($result, 'AI fix applied');
    }

    // =========================================================
    // SEED TOPIC GENERATION
    // =========================================================
    elseif ($method === 'POST' && $path === '/api/topics/seed-generate') {
        $projectId      = (int)($input('project_id') ?? 0);
        $pageTypeId     = (int)($input('page_type_id') ?? 0);
        $keywords       = $input('keywords', []);
        $countPerKw     = max(1, min(15, (int)($input('count_per_keyword') ?? 5)));
        if (!$projectId || !$pageTypeId) Response::error('project_id and page_type_id are required');
        if (empty($keywords) || !is_array($keywords)) Response::error('keywords array is required');
        $topics = (new ContentExtras())->generateTopicsFromSeed($projectId, $pageTypeId, $keywords, $countPerKw);
        Response::success(['topics' => $topics], count((array)$topics) . ' topics generated');
    }
    elseif ($method === 'POST' && $path === '/api/topics/seed-save') {
        $projectId  = (int)($input('project_id') ?? 0);
        $pageTypeId = (int)($input('page_type_id') ?? 0);
        $topics     = $input('topics', []);
        if (!$projectId || !$pageTypeId || empty($topics)) Response::error('project_id, page_type_id and topics required');
        $rows = [];
        foreach ((array)$topics as $t) {
            if (empty($t['title']) || empty($t['primary_keyword'])) continue;
            $rows[] = [
                'project_id'          => $projectId,
                'page_type_id'        => $pageTypeId,
                'title'               => $t['title'],
                'primary_keyword'     => $t['primary_keyword'],
                'supporting_keywords' => $t['supporting_keywords'] ?? null,
                'search_intent'       => $t['search_intent'] ?? 'informational',
                'content_angle'       => $t['content_angle'] ?? null,
                'target_word_count'   => (int)($t['target_word_count'] ?? 1200),
                'status'              => 'pending',
            ];
        }
        $count = (new Topic())->bulkCreate($rows);
        Response::success(['count' => $count], "{$count} topics saved");
    }

    // =========================================================
    // PAGE TYPES
    // =========================================================
    elseif ($method === 'GET' && $path === '/api/page-types') {
        Response::success((new PageType())->all());
    }

    // =========================================================
    // PROMPT TEMPLATES
    // =========================================================
    elseif ($method === 'GET' && $path === '/api/templates') {
        $pageTypeId = $input('page_type_id');
        $tpl = new PromptTemplate();
        $data = $pageTypeId ? $tpl->forPageType((int)$pageTypeId) : $tpl->all();
        Response::success($data);
    }

    // =========================================================
    // STATS / DASHBOARD
    // =========================================================
    elseif ($method === 'GET' && $path === '/api/stats') {
        $db = Database::getInstance();
        Response::success([
            'projects'          => $db->count('projects'),
            'topics'            => $db->count('topics'),
            'topics_pending'    => $db->count('topics', "status = 'pending'"),
            'topics_generated'  => $db->count('topics', "status = 'generated'"),
            'topics_failed'     => $db->count('topics', "status = 'failed'"),
            'content_total'     => $db->count('generated_content'),
            'content_approved'  => $db->count('generated_content', "status = 'approved'"),
            'content_draft'     => $db->count('generated_content', "status = 'draft'"),
        ]);
    }

    // =========================================================
    // RESEARCH MODULE
    // =========================================================
    elseif ($method === 'GET' && $path === '/api/research/get-models') {
        require __DIR__ . '/research/get-models.php';
    }
    elseif ($method === 'POST' && $path === '/api/research/generate-prompts') {
        require __DIR__ . '/research/generate-prompts.php';
    }
    elseif ($method === 'GET' && $path === '/api/research/fetch-projects') {
        require __DIR__ . '/research/fetch-projects.php';
    }
    elseif ($method === 'POST' && $path === '/api/research/add-prompts') {
        require __DIR__ . '/research/add-prompts.php';
    }
    elseif ($method === 'POST' && $path === '/api/research/run-prompt') {
        require __DIR__ . '/research/run-prompt.php';
    }
    elseif ($method === 'GET' && $path === '/api/research/fetch-prompts') {
        require __DIR__ . '/research/fetch-prompts.php';
    }
    elseif ($method === 'POST' && $path === '/api/research/delete-prompt') {
        require __DIR__ . '/research/delete-prompt.php';
    }
    elseif ($method === 'POST' && $path === '/api/research/add-single-prompt') {
        require __DIR__ . '/research/add-single-prompt.php';
    }
    // =========================================================
    // IMAGE OPTIMIZATION
    // =========================================================
    elseif ($method === 'POST' && $path === '/api/image-optimization/generate-meta') {
        require __DIR__ . '/image-optimization/generate-meta.php';
    }
    elseif ($method === 'GET' && $path === '/api/image-optimization/history') {
        require __DIR__ . '/image-optimization/get-history.php';
    }
    elseif ($method === 'GET' && $path === '/api/image-optimization/proxy-fetch') {
        require __DIR__ . '/image-optimization/proxy-fetch.php';
    }

    else {
        Response::error('Endpoint not found', 404);
    }

} catch (\Exception $e) {
    Response::error($e->getMessage(), 500);
}
