const express = require('express');
const sql = require('mssql');
const cors = require('cors');
const NodeCache = require('node-cache');
const fs = require('fs');
const path = require('path');
const pdfParse = require('pdf-parse');
const connectDB = require('../config/db');
const authRoutes = require("../src/routes/auth")
const LibraryRoute = require("../src/routes/Library")
const app = express();
app.use(cors());
app.use(express.json());
connectDB();
app.use("/api/auth" , authRoutes);

app.use("/api/lib",  LibraryRoute);

const sqlconfig = {
    server: '192.168.13.30',
    database: 'ocr',
    user: 'sa',
    password: 'sa@12345',
    options: {
        encrypt: false,
        trustServerCertificate: true,
    },
    pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000,
    },
    requestTimeout: 50000,
};

const searchCache = new NodeCache({ 
    stdTTL: 432000, // Cache persists for 5 days 
    checkperiod: 600 // Check expired keys every 10 minutes 
});

const pool = new sql.ConnectionPool(sqlconfig);
const poolConnect = pool.connect();

pool.on('error', (err) => {
    console.error('SQL Pool Error: ', err);
});

// Utility: Get relative file path
const getRelativePath = (fullPath) => {
    const basePath = '\\\\192.168.13.30\\c$\\GGN Office Repository\\';
    return fullPath.startsWith(basePath)
        ? fullPath.slice(basePath.length).replace(/\\/g, '/')
        : fullPath.replace(/\\/g, '/');
};

// Get a snippet of the text surrounding the keyword
const getSnippet = (text, keyword, contextLength = 100) => {
    const lowerText = text.toLowerCase();
    const lowerKeyword = keyword.toLowerCase();
    const startIndex = lowerText.indexOf(lowerKeyword);

    if (startIndex === -1) {
        return null;
    }

    const snippetStart = Math.max(0, startIndex - contextLength);
    const snippetEnd = Math.min(text.length, startIndex + keyword.length + contextLength);
    const snippet = text.substring(snippetStart, snippetEnd);

    return `...${snippet}...`;
};

// Extract keyword matches with snippets
const extractKeywordMatches = async (pdfPath, keyword) => {
    try {
        if (!fs.existsSync(pdfPath)) {
            console.warn(`File not found: ${pdfPath}`);
            return [];
        }

        const dataBuffer = fs.readFileSync(pdfPath);

        if (path.extname(pdfPath).toLowerCase() !== '.pdf') {
            console.warn(`File is not a PDF: ${pdfPath}`);
            return [];
        }

        const pdfData = await pdfParse(dataBuffer);
        const matches = [];
        const pages = pdfData.text.split('\n\n'); // Assuming pages are split by \n\n

        for (let pageIndex = 0; pageIndex < pages.length; pageIndex++) {
            const pageText = pages[pageIndex];

            if (pageText.toLowerCase().includes(keyword.toLowerCase())) {
                const snippet = getSnippet(pageText, keyword, 100);
                matches.push({
                    page: pageIndex - 1, // 1-based page number
                    snippet,
                });
            }
        }

        return matches;
    } catch (error) {
        console.error(`Error extracting keyword matches from: ${pdfPath}`, error);
        return [];
    }
};

// Search endpoint
app.get('/search', async (req, res) => {
    const { keyword, exclude } = req.query;

    if (!keyword || keyword.trim() === '') {
        return res.status(400).json({ error: 'No search keyword provided.' });
    }

    const cacheKey = `search:${keyword}:${exclude || 'noexclude'}`;
    const cachedResults = searchCache.get(cacheKey);

    if (cachedResults) {
        console.log(`Cache HIT for key: ${cacheKey}`);
        return res.json(cachedResults);
    }

    console.log(`Cache MISS for key: ${cacheKey}`);

    try {
        await poolConnect;
        const request = pool.request();

        const sanitizedKeyword = keyword.replace(/[^\w\s\+\-]/g, '').trim();
        if (!sanitizedKeyword) {
            return res.status(400).json({ error: 'Invalid search keyword' });
        }

        const terms = sanitizedKeyword.split('+').map(term => term.trim()).filter(Boolean);

        let query = 'SELECT Filename FROM files WHERE PdfData LIKE @term0';
        request.input('term0', sql.NVarChar, `%${terms[0]}%`);

        terms.slice(1).forEach((term, index) => {
            query += ` AND PdfData LIKE @term${index + 1}`;
            request.input(`term${index + 1}`, sql.NVarChar, `%${term}%`);
        });

        if (exclude && exclude.trim() !== '') {
            const excludedWords = exclude.split(/\s+/).filter(Boolean);
            excludedWords.forEach((word, index) => {
                const sanitizedExclude = word.replace(/[^\w\s]/g, '').trim();
                if (sanitizedExclude) {
                    query += ` AND PdfData NOT LIKE @exclude${index}`;
                    request.input(`exclude${index}`, sql.NVarChar, `%${sanitizedExclude}%`);
                }
            });
        }

        console.log('Executing SQL Query:', query);

        const result = await request.query(query);
        const responseData = [];

        console.log(`${result.recordset.length} records found`);

        for (const record of result.recordset) {
            const fullPath = record.Filename;

            if (path.extname(fullPath).toLowerCase() !== '.pdf') {
                console.log(`Skipping non-PDF file: ${fullPath}`);
                continue;
            }

            const relativePath = getRelativePath(fullPath);
            const absolutePath = path.join('\\\\192.168.13.30\\c$\\GGN Office Repository', relativePath);

            const matches = await extractKeywordMatches(absolutePath, keyword);

            responseData.push({
                Filename: fullPath,
                relativePath,
                matches
            });
        }

        searchCache.set(cacheKey, responseData);
        res.json(responseData);

    } catch (error) {
        console.error('Error processing search:', error);
        res.status(500).json({ error: 'An error occurred while processing your search.' });
    }
});


app.get('/files/*', (req, res) => {
    const relativePath = req.params[0];
    const basePath = '\\\\192.168.13.30\\c$\\GGN Office Repository';
    const filePath = path.join(basePath, relativePath);

    try {
        fs.accessSync(filePath, fs.constants.R_OK);
        res.sendFile(filePath);
    } catch (err) {
        console.error(`Error accessing file: ${filePath}`, err);
        res.status(404).json({ error: 'File not found or inaccessible' });
    }
});


app.get('/db-test', async (req, res) => {
    try {
        await pool.connect();
        res.status(200).json({ status: 'success', message: 'Database connection successful' });
    } catch (error) {
        console.error('Database connection error:', error.message);
        res.status(500).json({ status: 'error', message: 'Database connection failed' });
    }
});

app.post('/api/lib/library/add', (req, res) => {
    const { filename, originalFilePath } = req.body;
    const token = req.headers.authorization?.split(' ')[1]; 

    if (!token) {
        return res.status(401).json({ error: 'Unauthorized access' });
    }

    try {
        
        res.status(201).json({ message: 'File added to library successfully', filename });
    } catch (error) {
        console.error('Error adding file to library:', error.message);
        res.status(500).json({ error: 'Failed to add file to library' });
    }
});


app.use((req, res) => {
    res.status(404).json({ status: 'error', message: 'Route not found' });
});


const PORT = process.env.PORT || 3006;
app.listen(PORT, '192.168.7.206', () => {
    console.log(`Server running at http://192.168.7.206:${PORT}`);
});   this is api.js ache MISS for key: search:Ankita Gupta:noexclude
Executing SQL Query: SELECT Filename FROM files WHERE PdfData LIKE @term0
1 records found   wich returns somthing like this then after this i got the results on my frontend import React, { useState, useEffect } from 'react';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import { useNavigate } from 'react-router-dom';
import './Home.css';

const Home = () => {
    const [searchTerm, setSearchTerm] = useState('');
    const [excludeWords, setExcludeWords] = useState('');
    const [searchResults, setSearchResults] = useState([]);
    const [error, setError] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const navigate = useNavigate();

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (!token) {
            console.log("User is not logged in");
        }
    }, []);

    // Handle search term input
    const handleSearchTermChange = (event) => {
        setSearchTerm(event.target.value);
    };

    // Handle exclude-word input
    const handleExcludeWordsChange = (event) => {
        setExcludeWords(event.target.value);
    };

    // Add to Library Action
    const handleAddToLibrary = async (pdf) => {
        const token = localStorage.getItem('token');
        if (!token) {
            navigate('/login', {
                state: {
                    message: 'Please log in to add documents to your library',
                    redirectAfterLogin: '/home',
                },
            });
            return;
        }

        try {
            const response = await fetch('http://192.168.7.206:3006/api/lib/library/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`,
                },
                body: JSON.stringify({
                    filename: pdf.relativePath,
                    originalFilePath: pdf.Filename,
                }),
            });

            if (response.ok) {
                alert('Document added to library');
            } else {
                const errorData = await response.json();
                alert(errorData.message || 'Failed to add document to library');
            }
        } catch (error) {
            console.error('Error adding to library:', error);
            alert('Network error. Please try again.');
        }
    };

    // Form Submit for Search
    const handleSubmit = async (event) => {
        event.preventDefault();
        
        if (!searchTerm.trim()) {
            setError('Please enter a search term.');
            return;
        }

        setIsLoading(true);
        setError(null);

        try {
            const response = await fetch(
                `http://192.168.7.206:3006/search?keyword=${encodeURIComponent(searchTerm)}&exclude=${encodeURIComponent(
                    excludeWords || ''
                )}`
            );
            if (!response.ok) {
                throw new Error('Failed to fetch search results');
            }
            const data = await response.json();
            setSearchResults(data);
        } catch (error) {
            console.error(error);
            setError('Error fetching search results.');
        } finally {
            setIsLoading(false);
        }
    };

    // Handle Snippet Page Redirection
    const handleSnippetClick = (relativePath, page) => {
        const pdfUrl = `http://192.168.7.206:3006/files/${encodeURIComponent(relativePath)}#page=${page + 1}`;
        window.open(pdfUrl, '_blank');
    };

    return (
        <div className="app-container">
            <Navbar />
            <main>
                {/* Search Form */}
                <form onSubmit={handleSubmit} className="search-form">
                    <input
                        type="text"
                        placeholder="Enter search term"
                        value={searchTerm}
                        onChange={handleSearchTermChange}
                        className="search-input"
                    />
                    <input
                        type="text"
                        placeholder="Exclude words (optional)"
                        value={excludeWords}
                        onChange={handleExcludeWordsChange}
                        className="exclude-input"
                    />
                    <button
                        type="submit"
                        className="search-button"
                        disabled={isLoading}
                    >
                        {isLoading ? 'Searching...' : 'Search'}
                    </button>
                </form>

                {/* Error Message */}
                {error && <p className="error-message">{error}</p>}

                {/* Search Results */}
                <div className="results-container">
                    {isLoading ? (
                        <p className="loading">Loading results...</p>
                    ) : searchResults.length > 0 ? (
                        <div className="scrollable-container">
                            {searchResults.map((result, index) => (
                                <ResultCard
                                    key={index}
                                    result={result}
                                    handleSnippetClick={handleSnippetClick}
                                    onAddToLibrary={handleAddToLibrary}
                                    searchTerm={searchTerm}
                                />
                            ))}
                        </div>
                    ) : (
                        <p>No results found</p>
                    )}
                </div>
            </main>
            <Footer />
        </div>
    );
};

const ResultCard = ({ result, handleSnippetClick, onAddToLibrary, searchTerm }) => {
    const [isExpanded, setIsExpanded] = useState(false);

    return (
        <div className="result-card">
            <div className="result-header">
                <h3 className="filename">
                    <a
                        href={`http://192.168.7.206:3006/files/${result.relativePath}`}
                        target="_blank"
                        rel="noopener noreferrer"
                    >
                        {result.Filename.split('\\').pop()}
                    </a>
                </h3>
                <button
                    className="add-to-library-button"
                    onClick={() => onAddToLibrary(result)}
                    title="Add to Library"
                >
                    Add
                </button>
            </div>
            <p className="relative-path">
                <strong>Location:</strong> {result.relativePath}
            </p>

            {result.matches.length > 0 ? (
                <div className="matches">
                    <h4>Keyword Matches:</h4>
                    <div
                        className="match-snippet"
                        onClick={() =>
                            handleSnippetClick(result.relativePath, result.matches[0].page)
                        }
                    >
                        <strong>Page {result.matches[0].page + 1}:</strong>{' '}
                        <span
                            className="snippet-text"
                            dangerouslySetInnerHTML={{
                                __html: result.matches[0].snippet.replace(
                                    new RegExp(`(${searchTerm})`, 'gi'),
                                    '<b>$1</b>' // Bold matching keyword
                                ),
                            }}
                        />
                    </div>

                    {result.matches.length > 1 && (
                        <>
                            {isExpanded &&
                                result.matches.slice(1).map((match, matchIndex) => (
                                    <div
                                        key={matchIndex}
                                        className="match-snippet"
                                        onClick={() =>
                                            handleSnippetClick(result.relativePath, match.page)
                                        }
                                    >
                                        <strong>Page {match.page + 1}:</strong>{' '}
                                        <span
                                            className="snippet-text"
                                            dangerouslySetInnerHTML={{
                                                __html: match.snippet.replace(
                                                    new RegExp(`(${searchTerm})`, 'gi'),
                                                    '<b>$1</b>' // Bold matching keyword
                                                ),
                                            }}
                                        />
                                    </div>
                                ))}
                            <button
                                className="toggle-matches-btn"
                                onClick={() => setIsExpanded(!isExpanded)}
                            >
                                {isExpanded ? 'Show Less' : `Show More (${result.matches.length - 1})`}
                            </button>
                        </>
                    )}
                </div>
            ) : (
                <p className="no-matches">No matches found in this file.</p>
            )}
        </div>
    );
};

export default Home;    so now i want when the search returns no of documnets in terminla to be printed in fromtend also .....Ilike show somthing inetrsting like...their are 320 matches for your serach, wait a moment we will provide u the results ...then show the result continer and at the top add total no of doc found and index each card of pdf ...1 2 3 4 5 ...and so on