<?php

namespace App\Services;

use App\Models\Project;
use App\Models\Page;
use Illuminate\Support\Facades\Log;

class ScreamingFrogImporter
{
    /**
     * Import Screaming Frog CSV file
     */
    public function import(string $filePath, Project $project): int
    {
        if (!file_exists($filePath)) {
            throw new \Exception('CSV file not found: ' . $filePath);
        }

        $handle = fopen($filePath, 'r');
        if (!$handle) {
            throw new \Exception('Could not open CSV file');
        }

        // Read header row
        $headers = fgetcsv($handle);
        if (!$headers) {
            throw new \Exception('Invalid CSV file: no headers');
        }

        // Map header names to array indices
        $headerMap = array_flip(array_map('strtolower', $headers));

        $importedCount = 0;
        $rowNumber = 1;

        while (($row = fgetcsv($handle)) !== false) {
            $rowNumber++;

            try {
                $pageData = $this->extractPageData($row, $headerMap);

                // Skip non-HTML pages
                if (!$this->isValidPage($pageData)) {
                    continue;
                }

                // Detect page type from URL
                $pageData['page_type'] = $this->detectPageType($pageData['url']);

                // Create page record
                Page::create([
                    'project_id' => $project->id,
                    'url' => $pageData['url'],
                    'page_type' => $pageData['page_type'],
                    'title' => $pageData['title'] ?? null,
                    'meta_description' => $pageData['meta_description'] ?? null,
                    'h1' => $pageData['h1'] ?? null,
                    'h2s' => $pageData['h2s'] ?? null,
                    'word_count' => $pageData['word_count'] ?? null,
                    'status' => 'pending',
                ]);

                $importedCount++;

            } catch (\Exception $e) {
                Log::warning('Failed to import CSV row', [
                    'row' => $rowNumber,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        fclose($handle);

        // Update project total pages
        $project->update(['total_pages' => $importedCount]);

        Log::info('CSV import completed', [
            'project_id' => $project->id,
            'pages_imported' => $importedCount,
        ]);

        return $importedCount;
    }

    /**
     * Extract page data from CSV row
     */
    private function extractPageData(array $row, array $headerMap): array
    {
        $data = [];

        // Common Screaming Frog column names
        $columns = [
            'url' => ['address', 'url'],
            'title' => ['title 1', 'page title', 'title'],
            'meta_description' => ['meta description 1', 'meta description', 'description'],
            'h1' => ['h1-1', 'h1', 'h1 1'],
            'h2s' => ['h2-1', 'h2', 'h2 1'],
            'word_count' => ['word count', 'wordcount'],
        ];

        foreach ($columns as $field => $possibleNames) {
            foreach ($possibleNames as $name) {
                $lowerName = strtolower($name);
                if (isset($headerMap[$lowerName]) && isset($row[$headerMap[$lowerName]])) {
                    $data[$field] = trim($row[$headerMap[$lowerName]]);
                    break;
                }
            }
        }

        return $data;
    }

    /**
     * Check if page is valid for processing
     */
    private function isValidPage(array $pageData): bool
    {
        if (empty($pageData['url'])) {
            return false;
        }

        $url = strtolower($pageData['url']);

        // Skip common non-HTML files
        $excludeExtensions = ['.pdf', '.jpg', '.jpeg', '.png', '.gif', '.css', '.js', '.xml', '.txt'];
        foreach ($excludeExtensions as $ext) {
            if (str_ends_with($url, $ext)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Detect page type from URL pattern
     */
    private function detectPageType(string $url): string
    {
        $url = strtolower($url);

        // Homepage
        if (preg_match('#^https?://[^/]+/?$#', $url)) {
            return 'homepage';
        }

        // Product pages
        if (str_contains($url, '/product') || str_contains($url, '/item')) {
            return 'product';
        }

        // Collection/category pages
        if (str_contains($url, '/collection') || str_contains($url, '/category') || str_contains($url, '/shop')) {
            return 'collection';
        }

        // Blog posts
        if (str_contains($url, '/blog') || str_contains($url, '/article') || str_contains($url, '/post')) {
            return 'blog';
        }

        // Static pages
        if (str_contains($url, '/page') || str_contains($url, '/about') || str_contains($url, '/contact')) {
            return 'page';
        }

        return 'other';
    }
}
