library(ggplot2)
library(dplyr)
library(gridExtra)
library(scales)
library(grid)
library(RColorBrewer)
palette <- brewer.pal(8, "Dark2")

g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  if(length(leg) > 0) {
    legend <- tmp$grobs[[leg]]
    return(legend)
  } else {
    return(NULL)
  }
}

f <- list.files("results", pattern = "arbitrage_analysis_ETHUSDC_0x.*\\.csv$", full.names = TRUE)
d <- data.frame()
for(i in 1:length(f)) {
  t <- read.csv(f[i], stringsAsFactors = FALSE)
  t <- t[t$date != "TOTAL", ]
  t$pair <- basename(f[i])
  t$pair <- gsub("arbitrage_analysis_ETHUSDC_", "", t$pair)
  t$pair <- gsub("\\.csv$", "", t$pair)
  t$pair <- paste0("0x", substr(t$pair, 3, 8))
  d <- rbind(d, t)
}

d$date <- as.Date(d$date)
d$swaps <- as.numeric(d$swaps)
d$total_profit <- as.numeric(d$total_profit)
d$fees <- as.numeric(d$fees)
d$vol_ratio <- as.numeric(d$vol_ratio)

# Szűrés szeptember 18-27 közötti időszakra (2025)
d <- d %>% filter(date >= as.Date("2025-09-18") & date <= as.Date("2025-09-27"))

# Ellenőrzés: van-e adat
if(nrow(d) == 0) {
  stop("Nincs adat a megadott időszakban (2025-09-18 - 2025-09-27). Ellenőrizd a dátumokat!")
}

cat("Talált sorok száma:", nrow(d), "\n")
cat("Dátum tartomány:", min(d$date), "-", max(d$date), "\n")

base_theme <- theme_minimal(base_size = 12) + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 10), 
        axis.text.y = element_text(size = 10), 
        axis.title = element_text(size = 12, face = "bold"), 
        plot.title = element_text(size = 14, face = "bold", hjust = 0.5), 
        legend.position = "top", 
        legend.title = element_blank(), 
        legend.text = element_text(size = 10), 
        panel.grid.minor = element_blank(),
        plot.tag = element_text(size = 16, face = "bold"))

p1 <- ggplot(d, aes(x = date, y = swaps, color = pair)) + 
  geom_line(linewidth = 1.1) + 
  geom_point(size = 1.8) + 
  scale_color_manual(values = palette) + 
  scale_x_date(date_breaks = "1 day", date_labels = "%m-%d") + 
  scale_y_continuous(labels = comma_format()) + 
  labs(x = "Date", y = "Number of Swaps", title = "Daily Swap Count", tag = "A") + 
  base_theme + 
  guides(color = guide_legend(nrow = 1))

p2 <- ggplot(d, aes(x = date, y = total_profit, color = pair)) + 
  geom_line(linewidth = 1.1) + 
  geom_point(size = 1.8) + 
  scale_color_manual(values = palette) + 
  scale_x_date(date_breaks = "1 day", date_labels = "%m-%d") + 
  scale_y_continuous(labels = dollar_format()) + 
  labs(x = "Date", y = "Total Profit (USDT)", title = "Daily Total Profit", tag = "B") + 
  base_theme + 
  theme(legend.position = "none")

p3 <- ggplot(d, aes(x = date, y = fees, color = pair)) + 
  geom_line(linewidth = 1.1) + 
  geom_point(size = 1.8) + 
  scale_color_manual(values = palette) + 
  scale_x_date(date_breaks = "1 day", date_labels = "%m-%d") + 
  scale_y_continuous(labels = dollar_format()) + 
  labs(x = "Date", y = "Fees (USDT)", title = "Daily Fees", tag = "C") + 
  base_theme + 
  theme(legend.position = "none")

p4 <- ggplot(d, aes(x = date, y = vol_ratio, color = pair)) + 
  geom_line(linewidth = 1.1) + 
  geom_point(size = 1.8) + 
  scale_color_manual(values = palette) + 
  scale_x_date(date_breaks = "1 day", date_labels = "%m-%d") + 
  scale_y_continuous(labels = comma_format()) + 
  labs(x = "Date", y = "Volume/Profit Ratio", title = "Volume to Profit Ratio", tag = "D") + 
  base_theme + 
  theme(legend.position = "none")

pdf("arbitrage_analysis_plots_pub.pdf", width = 11, height = 9)
lg <- g_legend(p1)
p1_no_leg <- p1 + theme(legend.position = "none")

if(!is.null(lg)) {
  grid.arrange(lg, arrangeGrob(p1_no_leg, p2, p3, p4, ncol = 2, nrow = 2), 
               ncol = 1, heights = c(0.1, 0.9), newpage = FALSE)
} else {
  grid.arrange(arrangeGrob(p1_no_leg, p2, p3, p4, ncol = 2, nrow = 2), 
               ncol = 1, newpage = FALSE)
}
dev.off()
cat("PDF saved as: arbitrage_analysis_plots_pub.pdf\n")
