package com.storycove.controller;

import com.storycove.dto.LibraryOverviewStatsDto;
import com.storycove.service.LibraryService;
import com.storycove.service.LibraryStatisticsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/libraries/{libraryId}/statistics")
public class LibraryStatisticsController {

    private static final Logger logger = LoggerFactory.getLogger(LibraryStatisticsController.class);

    @Autowired
    private LibraryStatisticsService statisticsService;

    @Autowired
    private LibraryService libraryService;

    /**
     * Get overview statistics for a library
     */
    @GetMapping("/overview")
    public ResponseEntity<?> getOverviewStatistics(@PathVariable String libraryId) {
        try {
            // Verify library exists
            if (libraryService.getLibraryById(libraryId) == null) {
                return ResponseEntity.notFound().build();
            }

            LibraryOverviewStatsDto stats = statisticsService.getOverviewStatistics(libraryId);
            return ResponseEntity.ok(stats);

        } catch (Exception e) {
            logger.error("Failed to get overview statistics for library: {}", libraryId, e);
            return ResponseEntity.internalServerError()
                    .body(new ErrorResponse("Failed to retrieve statistics: " + e.getMessage()));
        }
    }

    /**
     * Get top tags statistics
     */
    @GetMapping("/top-tags")
    public ResponseEntity<?> getTopTagsStatistics(
            @PathVariable String libraryId,
            @RequestParam(defaultValue = "20") int limit) {
        try {
            if (libraryService.getLibraryById(libraryId) == null) {
                return ResponseEntity.notFound().build();
            }

            var stats = statisticsService.getTopTagsStatistics(libraryId, limit);
            return ResponseEntity.ok(stats);

        } catch (Exception e) {
            logger.error("Failed to get top tags statistics for library: {}", libraryId, e);
            return ResponseEntity.internalServerError()
                    .body(new ErrorResponse("Failed to retrieve statistics: " + e.getMessage()));
        }
    }

    /**
     * Get top authors statistics
     */
    @GetMapping("/top-authors")
    public ResponseEntity<?> getTopAuthorsStatistics(
            @PathVariable String libraryId,
            @RequestParam(defaultValue = "10") int limit) {
        try {
            if (libraryService.getLibraryById(libraryId) == null) {
                return ResponseEntity.notFound().build();
            }

            var stats = statisticsService.getTopAuthorsStatistics(libraryId, limit);
            return ResponseEntity.ok(stats);

        } catch (Exception e) {
            logger.error("Failed to get top authors statistics for library: {}", libraryId, e);
            return ResponseEntity.internalServerError()
                    .body(new ErrorResponse("Failed to retrieve statistics: " + e.getMessage()));
        }
    }

    /**
     * Get rating statistics
     */
    @GetMapping("/ratings")
    public ResponseEntity<?> getRatingStatistics(@PathVariable String libraryId) {
        try {
            if (libraryService.getLibraryById(libraryId) == null) {
                return ResponseEntity.notFound().build();
            }

            var stats = statisticsService.getRatingStatistics(libraryId);
            return ResponseEntity.ok(stats);

        } catch (Exception e) {
            logger.error("Failed to get rating statistics for library: {}", libraryId, e);
            return ResponseEntity.internalServerError()
                    .body(new ErrorResponse("Failed to retrieve statistics: " + e.getMessage()));
        }
    }

    /**
     * Get source domain statistics
     */
    @GetMapping("/source-domains")
    public ResponseEntity<?> getSourceDomainStatistics(
            @PathVariable String libraryId,
            @RequestParam(defaultValue = "10") int limit) {
        try {
            if (libraryService.getLibraryById(libraryId) == null) {
                return ResponseEntity.notFound().build();
            }

            var stats = statisticsService.getSourceDomainStatistics(libraryId, limit);
            return ResponseEntity.ok(stats);

        } catch (Exception e) {
            logger.error("Failed to get source domain statistics for library: {}", libraryId, e);
            return ResponseEntity.internalServerError()
                    .body(new ErrorResponse("Failed to retrieve statistics: " + e.getMessage()));
        }
    }

    /**
     * Get reading progress statistics
     */
    @GetMapping("/reading-progress")
    public ResponseEntity<?> getReadingProgressStatistics(@PathVariable String libraryId) {
        try {
            if (libraryService.getLibraryById(libraryId) == null) {
                return ResponseEntity.notFound().build();
            }

            var stats = statisticsService.getReadingProgressStatistics(libraryId);
            return ResponseEntity.ok(stats);

        } catch (Exception e) {
            logger.error("Failed to get reading progress statistics for library: {}", libraryId, e);
            return ResponseEntity.internalServerError()
                    .body(new ErrorResponse("Failed to retrieve statistics: " + e.getMessage()));
        }
    }

    /**
     * Get reading activity statistics (last week)
     */
    @GetMapping("/reading-activity")
    public ResponseEntity<?> getReadingActivityStatistics(@PathVariable String libraryId) {
        try {
            if (libraryService.getLibraryById(libraryId) == null) {
                return ResponseEntity.notFound().build();
            }

            var stats = statisticsService.getReadingActivityStatistics(libraryId);
            return ResponseEntity.ok(stats);

        } catch (Exception e) {
            logger.error("Failed to get reading activity statistics for library: {}", libraryId, e);
            return ResponseEntity.internalServerError()
                    .body(new ErrorResponse("Failed to retrieve statistics: " + e.getMessage()));
        }
    }

    // Error response DTO
    private static class ErrorResponse {
        private String error;

        public ErrorResponse(String error) {
            this.error = error;
        }

        public String getError() {
            return error;
        }
    }
}
