<?php
namespace App\Controllers;

use App\Repositories\AiRepository;
use App\Services\AiContextService;
use App\Services\AiRecommendationService;
use App\Utils\Sanitizer;
use RuntimeException;
use Throwable;

class AiController extends ApiController
{
    private AiRecommendationService $ai;
    private AiContextService $context;
    private AiRepository $requests;

    public function __construct(AiRecommendationService $ai, AiContextService $context, AiRepository $requests)
    {
        $this->ai = $ai;
        $this->context = $context;
        $this->requests = $requests;
    }

    public function chat(): void
    {
        $message = Sanitizer::sanitize($_POST['message'] ?? '');
        if ($message === '') {
            $this->errorResponse('message is required');
        }
        $this->runContextFeature('chat', function () use ($message) {
            return $this->context->chatContext(
                $message,
                Sanitizer::sanitize($_POST['screen'] ?? ''),
                Sanitizer::sanitize($_POST['entity_type'] ?? ''),
                Sanitizer::sanitize($_POST['entity_id'] ?? '')
            );
        });
    }

    public function customerBrief(): void
    {
        $contactId = Sanitizer::sanitize($_POST['contact_id'] ?? $_GET['contact_id'] ?? '');
        if ($contactId === '') {
            $this->errorResponse('contact_id is required');
        }
        $this->runContextFeature('customer_brief', function () use ($contactId) {
            return $this->context->customerBriefContext($contactId);
        }, 'customer', $contactId);
    }

    public function dealRisk(): void
    {
        $dealId = Sanitizer::sanitize($_POST['deal_id'] ?? $_GET['deal_id'] ?? '');
        if ($dealId === '') {
            $this->errorResponse('deal_id is required');
        }
        $this->runContextFeature('deal_risk', function () use ($dealId) {
            return $this->context->dealRiskContext($dealId);
        }, 'deal', $dealId);
    }

    public function activityDraft(): void
    {
        $contactId = Sanitizer::sanitize($_POST['contact_id'] ?? '');
        $dealId = Sanitizer::sanitize($_POST['deal_id'] ?? '');
        $intent = Sanitizer::sanitize($_POST['intent'] ?? '');
        $entityType = $dealId !== '' ? 'deal' : 'customer';
        $entityId = $dealId !== '' ? $dealId : $contactId;
        $this->runContextFeature('activity_draft', function () use ($contactId, $dealId, $intent) {
            return $this->context->activityDraftContext($contactId, $dealId, $intent);
        }, $entityType, $entityId);
    }

    public function kpiExplain(): void
    {
        $this->runContextFeature('kpi_explain', function () {
            return $this->context->kpiExplainContext($this->readJsonArray('filters'));
        });
    }

    public function operationRuleDraft(): void
    {
        $instruction = Sanitizer::sanitize($_POST['instruction'] ?? '');
        if ($instruction === '') {
            $this->errorResponse('instruction is required');
        }
        $this->runContextFeature('operation_rule_draft', function () use ($instruction) {
            return $this->context->operationRuleDraftContext($instruction);
        }, 'operation_rule', '');
    }

    public function feedback(): void
    {
        if (!$this->ai->enabled()) {
            $this->errorResponse('AI feature is disabled', 404);
        }
        $requestId = (int)($_POST['ai_request_id'] ?? 0);
        if ($requestId <= 0 || !$this->requests->findRequest($requestId)) {
            $this->errorResponse('AI request not found', 404);
        }
        $id = $this->requests->createFeedback(
            $requestId,
            (int)($_SESSION['user_id'] ?? 0),
            (int)($_POST['rating'] ?? 0),
            (int)($_POST['accepted'] ?? 0) === 1,
            Sanitizer::sanitize($_POST['comment'] ?? '')
        );
        $this->successResponse(['feedback_id' => $id], 'Feedback saved');
    }

    private function runContextFeature(string $featureKey, callable $contextFactory, string $entityType = '', string $entityId = ''): void
    {
        if (!$this->ai->enabled()) {
            $this->errorResponse('AI feature is disabled', 404);
        }
        if (!$this->ai->configured()) {
            $this->errorResponse('OpenAI API key is not configured', 503);
        }

        try {
            $context = $contextFactory();
            if (!is_array($context)) {
                throw new RuntimeException('AI context could not be built');
            }
            $this->successResponse($this->ai->run($featureKey, $context, $entityType, $entityId));
        } catch (RuntimeException $e) {
            $code = $this->statusCodeFor($e->getMessage());
            $this->errorResponse($e->getMessage(), $code);
        } catch (Throwable $e) {
            $this->errorResponse('AI request failed', 500);
        }
    }

    private function statusCodeFor(string $message): int
    {
        if (stripos($message, 'Forbidden') !== false) {
            return 403;
        }
        if (stripos($message, 'not found') !== false) {
            return 404;
        }
        if (stripos($message, 'not configured') !== false) {
            return 503;
        }
        return 400;
    }

    private function readJsonArray(string $key): array
    {
        $raw = $_POST[$key] ?? $_REQUEST[$key] ?? '[]';
        if (is_array($raw)) {
            return $raw;
        }
        $data = json_decode((string)$raw, true);
        return is_array($data) ? $data : [];
    }
}
