<?php
namespace App\Services;

class AiPromptService
{
    public function promptVersion(): string
    {
        return 'phase1-v1';
    }

    public function systemPrompt(string $featureKey): string
    {
        $base = 'You are the SaleOS AI assistant for a Persian/RTL CRM. Use only the provided context. Do not invent records, IDs, payment facts, or policy. Keep output concise, actionable, and safe for a salesperson or manager. If evidence is weak, say so in the returned JSON. Do not include raw SQL or instructions that directly mutate data.';

        $featurePrompts = [
            'chat' => 'Answer the user question using the scoped CRM context. If CRM rows or summaries are provided, answer directly from those records and do not say you lack data access. If the requested data is absent from context, say which scoped data was unavailable. Prefer practical next steps and cite the source_ref labels by name when relevant.',
            'customer_brief' => 'Create a customer brief for a sales/support user before they contact this customer.',
            'deal_risk' => 'Assess the deal risk and propose recovery actions. Focus on status, payment, activity freshness, and missing follow-up.',
            'activity_draft' => 'Draft a CRM activity note/follow-up plan. It must be human-reviewable and not claim that a message was sent.',
            'kpi_explain' => 'Explain KPI movement using the provided aggregate metrics. Avoid causal certainty unless the data supports it.',
            'operation_rule_draft' => 'Draft an Operation Manager rule JSON only from the allowed fields and actions. Never execute, never include SQL, and include warnings for anything that needs human approval.',
        ];

        return $base . ' ' . ($featurePrompts[$featureKey] ?? '');
    }

    public function schema(string $featureKey): array
    {
        $schemas = [
            'chat' => $this->chatSchema(),
            'customer_brief' => $this->customerBriefSchema(),
            'deal_risk' => $this->dealRiskSchema(),
            'activity_draft' => $this->activityDraftSchema(),
            'kpi_explain' => $this->kpiExplainSchema(),
            'operation_rule_draft' => $this->operationRuleDraftSchema(),
        ];

        return $schemas[$featureKey] ?? $this->chatSchema();
    }

    private function chatSchema(): array
    {
        return $this->objectSchema('saleos_ai_chat', [
            'answer' => ['type' => 'string'],
            'next_actions' => $this->stringArray(),
            'source_refs' => $this->stringArray(),
            'confidence' => ['type' => 'number'],
            'needs_human_review' => ['type' => 'boolean'],
        ]);
    }

    private function customerBriefSchema(): array
    {
        return $this->objectSchema('saleos_customer_brief', [
            'summary' => ['type' => 'string'],
            'signals' => $this->stringArray(),
            'risks' => $this->stringArray(),
            'next_actions' => $this->actionArray(),
            'draft_message' => ['type' => 'string'],
            'confidence' => ['type' => 'number'],
            'needs_human_review' => ['type' => 'boolean'],
        ]);
    }

    private function dealRiskSchema(): array
    {
        return $this->objectSchema('saleos_deal_risk', [
            'risk_level' => ['type' => 'string', 'enum' => ['low', 'medium', 'high']],
            'risk_score' => ['type' => 'integer', 'minimum' => 0, 'maximum' => 100],
            'reasons' => $this->stringArray(),
            'blockers' => $this->stringArray(),
            'recovery_plan' => $this->stringArray(),
            'next_activity' => ['type' => 'string'],
            'confidence' => ['type' => 'number'],
            'needs_human_review' => ['type' => 'boolean'],
        ]);
    }

    private function activityDraftSchema(): array
    {
        return $this->objectSchema('saleos_activity_draft', [
            'activity_type' => ['type' => 'string'],
            'title' => ['type' => 'string'],
            'note' => ['type' => 'string'],
            'due_suggestion' => ['type' => 'string'],
            'talking_points' => $this->stringArray(),
            'follow_up_question' => ['type' => 'string'],
            'confidence' => ['type' => 'number'],
        ]);
    }

    private function kpiExplainSchema(): array
    {
        return $this->objectSchema('saleos_kpi_explain', [
            'headline' => ['type' => 'string'],
            'drivers' => $this->stringArray(),
            'anomalies' => $this->stringArray(),
            'recommendations' => $this->stringArray(),
            'caveats' => $this->stringArray(),
            'confidence' => ['type' => 'number'],
        ]);
    }

    private function operationRuleDraftSchema(): array
    {
        $schema = $this->objectSchema('saleos_operation_rule_draft', [
            'rule_name' => ['type' => 'string'],
            'description' => ['type' => 'string'],
            'filter' => ['type' => 'object', 'additionalProperties' => true],
            'condition' => ['type' => 'object', 'additionalProperties' => true],
            'operation' => ['type' => 'object', 'additionalProperties' => true],
            'warnings' => $this->stringArray(),
            'confidence' => ['type' => 'number'],
            'needs_human_review' => ['type' => 'boolean'],
        ]);
        $schema['strict'] = false;
        return $schema;
    }

    private function objectSchema(string $name, array $properties): array
    {
        return [
            'name' => $name,
            'strict' => true,
            'schema' => [
                'type' => 'object',
                'additionalProperties' => false,
                'properties' => $properties,
                'required' => array_keys($properties),
            ],
        ];
    }

    private function stringArray(): array
    {
        return [
            'type' => 'array',
            'items' => ['type' => 'string'],
        ];
    }

    private function actionArray(): array
    {
        return [
            'type' => 'array',
            'items' => [
                'type' => 'object',
                'additionalProperties' => false,
                'properties' => [
                    'title' => ['type' => 'string'],
                    'rationale' => ['type' => 'string'],
                    'priority' => ['type' => 'string', 'enum' => ['low', 'medium', 'high']],
                ],
                'required' => ['title', 'rationale', 'priority'],
            ],
        ];
    }
}
