#include "video_player.h"

#include <algorithm>
#include <fstream>
#include <sstream>

extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
}

bool AnimationCatalog::Load(const std::string& assets_dir) {
    assets_dir_ = assets_dir;
    videos_.clear();
    posters_.clear();
    std::ifstream input(assets_dir + "/catalog.tsv");
    if (!input) return false;
    std::string line;
    std::getline(input, line);  // header
    while (std::getline(input, line)) {
        std::istringstream row(line);
        std::string id, key, instruction, video, poster;
        if (!std::getline(row, id, '\t') || !std::getline(row, key, '\t') ||
            !std::getline(row, instruction, '\t') || !std::getline(row, video, '\t') ||
            !std::getline(row, poster, '\t'))
            return false;
        if (id.empty() || video.empty()) return false;
        videos_[id] = video;
        posters_[id] = poster;
    }
    return !videos_.empty();
}

std::string AnimationCatalog::PosterPathFor(const std::string& id) const {
    auto it = posters_.find(id);
    return it == posters_.end() ? std::string{} : assets_dir_ + "/" + it->second;
}

std::string AnimationCatalog::PathFor(const std::string& id) const {
    auto it = videos_.find(id);
    return it == videos_.end() ? std::string{} : assets_dir_ + "/" + it->second;
}

VideoPlayer::~VideoPlayer() { Close(); }

bool VideoPlayer::Open(const std::string& path, int width, int height, bool letterbox) {
    Close();
    if (avformat_open_input(&format_, path.c_str(), nullptr, nullptr) < 0 ||
        avformat_find_stream_info(format_, nullptr) < 0) { Close(); return false; }
    stream_ = av_find_best_stream(format_, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
    if (stream_ < 0) { Close(); return false; }
    AVStream* stream = format_->streams[stream_];
    const AVCodec* decoder = avcodec_find_decoder(stream->codecpar->codec_id);
    if (!decoder) { Close(); return false; }
    codec_ = avcodec_alloc_context3(decoder);
    if (!codec_ || avcodec_parameters_to_context(codec_, stream->codecpar) < 0 ||
        avcodec_open2(codec_, decoder, nullptr) < 0) { Close(); return false; }
    frame_ = av_frame_alloc();
    packet_ = av_packet_alloc();
    width_ = width;
    height_ = height;
    letterbox_ = letterbox;
    scaled_width_ = width;
    scaled_height_ = height;
    if (letterbox_) {
        const double scale = std::min(double(width) / codec_->width,
                                      double(height) / codec_->height);
        scaled_width_ = std::max(1, std::min(width, int(codec_->width * scale + .5)));
        scaled_height_ = std::max(1, std::min(height, int(codec_->height * scale + .5)));
        scaled_pixels_.resize(static_cast<size_t>(scaled_width_) * scaled_height_ * 4);
    }
    pixels_.resize(static_cast<size_t>(width_) * height_ * 4);
    scaler_ = sws_getContext(codec_->width, codec_->height, codec_->pix_fmt,
                             scaled_width_, scaled_height_, AV_PIX_FMT_BGRA, SWS_BILINEAR,
                             nullptr, nullptr, nullptr);
    skip_ = 3;
    const AVRational rate = av_guess_frame_rate(format_, stream, nullptr);
    if (stream->codecpar->codec_id == AV_CODEC_ID_MJPEG) skip_ = 1;
    else if (rate.num > 0 && rate.den > 0)
        skip_ = std::max(1, static_cast<int>(av_q2d(rate) / 10.0 + 0.5));
    if (!frame_ || !packet_ || !scaler_) { Close(); return false; }
    return true;
}

bool VideoPlayer::DecodeOne() {
    for (int attempt = 0; attempt < 1000; ++attempt) {
        const int result = avcodec_receive_frame(codec_, frame_);
        if (result == 0) return true;
        if (result != AVERROR(EAGAIN) && result != AVERROR_EOF) return false;
        const int read = av_read_frame(format_, packet_);
        if (read < 0) {
            if (av_seek_frame(format_, stream_, 0, AVSEEK_FLAG_BACKWARD) < 0) return false;
            avcodec_flush_buffers(codec_);
            continue;
        }
        if (packet_->stream_index == stream_) {
            const int sent = avcodec_send_packet(codec_, packet_);
            av_packet_unref(packet_);
            if (sent < 0 && sent != AVERROR(EAGAIN)) return false;
        } else {
            av_packet_unref(packet_);
        }
    }
    return false;
}

bool VideoPlayer::NextFrame() {
    if (!codec_ || !scaler_) return false;
    for (int i = 0; i < skip_; ++i)
        if (!DecodeOne()) return false;
    uint8_t* destination[4] = {letterbox_ ? scaled_pixels_.data() : pixels_.data(),
                               nullptr, nullptr, nullptr};
    const int stride[4] = {scaled_width_ * 4, 0, 0, 0};
    if (sws_scale(scaler_, frame_->data, frame_->linesize, 0,
                  codec_->height, destination, stride) != scaled_height_) return false;
    if (letterbox_) {
        for (size_t i = 0; i < pixels_.size(); i += 4) {
            pixels_[i] = 0x45; pixels_[i + 1] = 0x3F;
            pixels_[i + 2] = 0x24; pixels_[i + 3] = 0xFF;
        }
        const int off_x = (width_ - scaled_width_) / 2;
        const int off_y = (height_ - scaled_height_) / 2;
        for (int y = 0; y < scaled_height_; ++y)
            std::copy_n(scaled_pixels_.data() + static_cast<size_t>(y) * scaled_width_ * 4,
                        static_cast<size_t>(scaled_width_) * 4,
                        pixels_.data() + (static_cast<size_t>(y + off_y) * width_ + off_x) * 4);
    }
    return true;
}

void VideoPlayer::Close() {
    if (scaler_) sws_freeContext(scaler_);
    if (packet_) av_packet_free(&packet_);
    if (frame_) av_frame_free(&frame_);
    if (codec_) avcodec_free_context(&codec_);
    if (format_) avformat_close_input(&format_);
    scaler_ = nullptr;
    stream_ = -1;
    pixels_.clear();
    scaled_pixels_.clear();
}
