<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\AiJob;
use App\Models\Proposal;
use App\Models\ProposalRequest;
use App\Jobs\GenerateProposalJob;
use App\Models\ProposalSection;
use App\Models\ProposalSectionAudit;
use App\Models\User;
use App\Models\Brand;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;

class AiProposalController extends Controller
{
    /**
     * Show the form for creating a new AI proposal request.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // Get all brands for the dropdown
        $brands = Brand::all();
        
        // Get all creators for the dropdown
        $creators = User::whereHas('roles', function ($q) {
            $q->where('name', 'creator');
        })->get();
        
        return view('superadmin.ai-proposals.create', compact('brands', 'creators'));
    }
    
    /**
     * Store a new AI proposal request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Validate inputs
        $validated = $request->validate([
            'target_brand_id' => 'required|exists:brands,id',
            'creator_id' => 'nullable|exists:users,id',
            'campaign_brief' => 'required|string|max:5000',
            'tone' => 'required|string|max:255',
            'budget_range' => 'required|array|size:2',
            'budget_range.*' => 'numeric|min:0',
            'deliverables' => 'required|array',
            'deliverables.*' => 'string|max:255',
            'reason' => 'required|string|max:1000',
        ]);
        
        // Get the target brand
        $brand = Brand::findOrFail($validated['target_brand_id']);
        
        // Sanitize PII with stricter rules for Super Admin
        $sanitizedBrief = $this->sanitizePiiStrict($validated['campaign_brief']);
        
        // Create proposal request with Super Admin metadata
        $proposalRequest = ProposalRequest::create([
            'brand_id' => $brand->id,
            'creator_id' => $validated['creator_id'] ?? null,
            'campaign_brief' => $sanitizedBrief,
            'tone' => $validated['tone'],
            'budget_range' => $validated['budget_range'],
            'deliverables' => $validated['deliverables'],
            'status' => 'pending',
        ]);
        
        // Enqueue AI job
        $aiJob = $this->enqueueAiJob($brand->id, $validated['creator_id'] ?? null, [
            'campaign_brief' => $sanitizedBrief,
            'tone' => $validated['tone'],
            'budget_range' => $validated['budget_range'],
            'deliverables' => $validated['deliverables'],
            'brand_name' => $brand->name,
            'brand_industry' => $brand->settings['industry'] ?? 'general',
        ]);
        
        // Link proposal request with AI job
        $proposalRequest->update(['ai_job_id' => $aiJob->id]);
        
        // Log the Super Admin action
        \App\Models\AuditLog::create([
            'actor_id' => Auth::id(),
            'action' => 'generate_ai_proposal',
            'target_type' => 'AiJob',
            'target_id' => $aiJob->id,
            'meta' => [
                'brand_id' => $brand->id,
                'creator_id' => $validated['creator_id'] ?? null,
                'reason' => $validated['reason'],
            ],
        ]);
        
        return response()->json([
            'success' => true,
            'message' => 'AI proposal generation started!',
            'job_id' => $aiJob->job_id,
        ]);
    }
    
    /**
     * Display a listing of AI jobs across all brands.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $aiJobs = AiJob::with(['brand', 'creator'])
            ->orderBy('created_at', 'desc')
            ->paginate(20);
            
        return view('superadmin.ai-proposals.index', compact('aiJobs'));
    }
    
    /**
     * Re-run an AI job with Super Admin privileges.
     *
     * @param  string  $jobId
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function rerun($jobId, Request $request)
    {
        $validated = $request->validate([
            'reason' => 'required|string|max:1000',
        ]);
        
        $aiJob = AiJob::where('job_id', $jobId)->firstOrFail();
        
        // Reset job status
        $aiJob->update([
            'status' => 'queued',
            'result_text' => null,
            'result_meta' => null,
            'provider' => null,
            'error_message' => null,
            'token_usage' => 0,
            'completed_at' => null,
        ]);
        
        // Get the original payload from the proposal request
        $proposalRequest = ProposalRequest::where('ai_job_id', $aiJob->id)->first();
        if (!$proposalRequest) {
            return redirect()->back()->with('error', 'Proposal request not found.');
        }
        
        $payload = [
            'campaign_brief' => $proposalRequest->campaign_brief,
            'tone' => $proposalRequest->tone,
            'budget_range' => $proposalRequest->budget_range,
            'deliverables' => $proposalRequest->deliverables,
            'brand_name' => $aiJob->brand->name,
            'brand_industry' => $aiJob->brand->settings['industry'] ?? 'general',
        ];
        
        // Dispatch the actual job
        GenerateProposalJob::dispatch($aiJob->id, $payload);
        
        // Log the Super Admin action
        \App\Models\AuditLog::create([
            'actor_id' => Auth::id(),
            'action' => 'regenerate_ai_proposal',
            'target_type' => 'AiJob',
            'target_id' => $aiJob->id,
            'meta' => [
                'reason' => $validated['reason'],
            ],
        ]);
        
        return redirect()->back()->with('success', 'AI job re-run successfully!');
    }
    
    /**
     * View token usage across brands.
     *
     * @return \Illuminate\Http\Response
     */
    public function tokenUsage()
    {
        $tokenUsage = AiJob::select('brand_id')
            ->selectRaw('SUM(token_usage) as total_tokens')
            ->groupBy('brand_id')
            ->with('brand')
            ->get();
            
        return view('superadmin.ai-proposals.token-usage', compact('tokenUsage'));
    }
    
    /**
     * Force refresh cache for an AI job.
     *
     * @param  string  $jobId
     * @return \Illuminate\Http\Response
     */
    public function forceRefresh($jobId)
    {
        $aiJob = AiJob::where('job_id', $jobId)->firstOrFail();
        
        // In a real implementation, you would clear any cached data related to this job
        // For now, we'll just log the action
        \App\Models\AuditLog::create([
            'actor_id' => Auth::id(),
            'action' => 'force_refresh_ai_job',
            'target_type' => 'AiJob',
            'target_id' => $aiJob->id,
            'meta' => [],
        ]);
        
        return redirect()->back()->with('success', 'Cache refreshed successfully!');
    }
    
    /**
     * Enqueue an AI job for proposal generation.
     *
     * @param  int  $brandId
     * @param  int|null  $creatorId
     * @param  array  $payload
     * @return \App\Models\AiJob
     */
    protected function enqueueAiJob($brandId, $creatorId, $payload)
    {
        $jobId = (string) Str::uuid();
        
        $aiJob = AiJob::create([
            'job_id' => $jobId,
            'type' => 'generate_proposal',
            'status' => 'queued',
            'brand_id' => $brandId,
            'creator_id' => $creatorId,
            'result_text' => null,
            'result_meta' => null,
            'provider' => null,
        ]);
        
        // Dispatch the actual job
        GenerateProposalJob::dispatch($aiJob->id, $payload);
        
        return $aiJob;
    }
    
    /**
     * Sanitize PII from text with stricter rules for Super Admin.
     *
     * @param  string  $text
     * @return string
     */
    protected function sanitizePiiStrict($text)
    {
        // Apply standard PII sanitization
        $text = $this->sanitizePii($text);
        
        // Apply additional strict sanitization for Super Admin
        // Remove names (simple pattern - any capitalized word)
        $text = preg_replace('/\b[A-Z][a-z]+\b/', '[NAME]', $text);
        
        // Remove addresses (simple pattern)
        $text = preg_replace('/\d+\s+[A-Za-z\s]+(?:Street|St|Avenue|Ave|Road|Rd|Boulevard|Blvd|Lane|Ln|Drive|Dr|Court|Ct|Place|Pl|Square|Sq|Terrace|Ter)\b/', '[ADDRESS]', $text);
        
        // Remove company names (simple pattern - multiple capitalized words)
        $text = preg_replace('/\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+){1,3}\b/', '[COMPANY]', $text);
        
        return $text;
    }
    
    /**
     * Sanitize PII from text before sending to AI service.
     *
     * @param  string  $text
     * @return string
     */
    protected function sanitizePii($text)
    {
        // Remove email addresses
        $text = preg_replace('/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/', '[EMAIL]', $text);
        
        // Remove phone numbers (various formats)
        $text = preg_replace('/(\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/', '[PHONE]', $text);
        
        // Remove URLs
        $text = preg_replace('/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/', '[URL]', $text);
        
        // Remove credit card numbers (simple pattern)
        $text = preg_replace('/\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/', '[CREDIT CARD]', $text);
        
        // Remove social security numbers
        $text = preg_replace('/\b\d{3}-\d{2}-\d{4}\b/', '[SSN]', $text);
        
        // Remove IP addresses
        $text = preg_replace('/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/', '[IP ADDRESS]', $text);
        
        return $text;
    }
}