<?php

namespace App\Services\Ai;

use App\Models\AiRun;
use App\Models\Meeting;
use App\Models\Opportunity;
use App\Models\ProjectMilestone;
use App\Models\ProposalVersion;
use Illuminate\Support\Collection;

class AiGenerationService
{
    public function summarizeMeeting(Meeting $meeting): AiRun
    {
        $note = $meeting->notes()->latest()->first();
        $payload = [
            'executive_summary' => str($note?->raw_notes ?? 'Meeting captured.')->limit(250)->toString(),
            'client_goals' => ['Clarify pain points', 'Align the consulting scope'],
            'current_challenges' => ['Manual workflows', 'Disconnected systems'],
            'systems_mentioned' => ['CRM', 'ERP', 'eCommerce stack'],
            'stakeholders' => [$meeting->contact?->name ?? 'Primary client contact'],
            'budget_indicators' => ['Budget to be confirmed during proposal drafting'],
            'timeline_indicators' => ['Discovery-led timeline'],
            'risks' => ['Requirements may evolve after deeper assessment'],
            'assumptions' => ['Human review required before sharing with client'],
            'recommended_next_steps' => ['Refine meeting notes', 'Generate draft proposal'],
            'proposal_recommendations' => ['Start with assessment engagement', 'Phase delivery by milestone'],
        ];

        return AiRun::create([
            'run_type' => 'meeting_summary',
            'status' => 'draft',
            'meeting_id' => $meeting->id,
            'opportunity_id' => $meeting->opportunity_id,
            'payload' => $payload,
            'draft_output' => $payload,
            'approved_output' => null,
        ]);
    }

    public function draftProposal(Opportunity $opportunity): ProposalVersion
    {
        $document = $opportunity->proposalDocuments()->firstOrCreate([
            'opportunity_id' => $opportunity->id,
        ], [
            'title' => ($opportunity->company_name ?: 'Client').' Proposal',
            'status' => 'draft',
            'client_contact_id' => $opportunity->primary_contact_id,
            'owner_user_id' => $opportunity->owner_user_id,
            'affiliate_user_id' => $opportunity->affiliate_user_id,
            'controlled_terms_status' => 'pending_review',
        ]);

        $content = [
            'cover_title' => 'Technology & AI Growth Proposal',
            'client_company_overview' => $opportunity->account?->name ?? $opportunity->company_name,
            'discovery_summary' => 'Drafted from discovery notes and questionnaire responses. Review and refine before sharing.',
            'business_objectives' => [
                'Modernize operations',
                'Improve visibility across systems',
                'Prioritize automation with measurable ROI',
            ],
            'recommended_solution' => [
                'Discovery and readiness assessment',
                'Roadmap and systems design',
                'Phased implementation support',
            ],
            'milestones' => [
                ['title' => 'Assessment', 'amount' => 3500],
                ['title' => 'Roadmap', 'amount' => 6500],
                ['title' => 'Implementation Sprint', 'amount' => 12000],
            ],
            'pricing_payment_schedule' => 'Milestone-based invoicing. Human review required before client delivery.',
            'engagement_terms' => 'Draft terms pending resident/executive review.',
            'controlled_terms' => true,
        ];

        return ProposalVersion::create([
            'proposal_document_id' => $document->id,
            'version_number' => (($document->versions()->max('version_number')) ?? 0) + 1,
            'status' => 'draft',
            'content' => $content,
            'rendered_html' => null,
            'change_summary' => 'Initial AI-assisted proposal draft.',
            'created_by_user_id' => $opportunity->owner_user_id,
        ]);
    }

    public function draftMilestones(ProposalVersion $proposalVersion): Collection
    {
        return collect($proposalVersion->content['milestones'] ?? [])->map(function (array $milestone, int $index) {
            return [
                'title' => $milestone['title'] ?? 'Milestone '.($index + 1),
                'description' => 'Drafted milestone generated from proposal scope.',
                'client_facing_description' => 'Shared milestone summary pending final review.',
                'amount' => $milestone['amount'] ?? 0,
                'sort_order' => $index + 1,
            ];
        });
    }

    public function draftTasks(ProjectMilestone $milestone): Collection
    {
        return collect([
            [
                'title' => $milestone->title.' Planning',
                'description' => 'Validate requirements and confirm acceptance criteria.',
            ],
            [
                'title' => $milestone->title.' Delivery',
                'description' => 'Execute the scoped work and update client-facing progress.',
            ],
        ]);
    }

    public function extractBusinessRulesFromChangeRequest(string $request): Collection
    {
        return collect([
            [
                'title' => 'Generated rule draft',
                'description' => str($request)->limit(300)->toString(),
                'rule_type' => 'workflow',
                'owner_role' => 'executive',
            ],
        ]);
    }
}
