library(readr)
library(dplyr)
library(plotly)

# --- Read and clean Bitcoin data ---
bitcoin <- read_csv("bitcoin_data.csv", 
                    locale = locale(decimal_mark = ",", grouping_mark = "."))
names(bitcoin)[names(bitcoin) == "Datum"] <- "date"
names(bitcoin)[names(bitcoin) == "Zuletzt"] <- "price"

bitcoin$date <- as.Date(bitcoin$date, format = "%d.%m.%Y")
bitcoin$price <- as.numeric(bitcoin$price)

# --- Read and clean US debt data ---
usa_debt <- read_csv("GFDEBTN.csv")
names(usa_debt)[names(usa_debt) == "GFDEBTN"] <- "debt"
usa_debt$observation_date <- as.Date(usa_debt$observation_date)

today <- as.Date("2025-08-04")
latest_debt <- tail(usa_debt$debt, 1)
usa_debt <- bind_rows(usa_debt, data.frame(observation_date = today, debt = latest_debt))

# --- Merge datasets ---
combined <- merge(usa_debt, bitcoin, by.x = "observation_date", by.y = "date")

# --- Scaling to align y-axes ---
min_debt <- min(combined$debt, na.rm = TRUE)
max_debt <- max(combined$debt, na.rm = TRUE)
min_price <- min(combined$price, na.rm = TRUE)
max_price <- max(combined$price, na.rm = TRUE)

a <- (max_debt - min_debt) / (max_price - min_price)
b <- min_debt - a * min_price
combined$price_scaled <- a * combined$price + b
fig <- plot_ly() %>%
  add_lines(
    data = combined,
    x = ~observation_date,
    y = ~debt,
    name = "US Debt",
    line = list(color = "blue"),
    yaxis = "y1"
  ) %>%
  add_lines(
    data = combined,
    x = ~observation_date,
    y = ~price_scaled,
    name = "Bitcoin Price",
    line = list(color = "orange"),
    yaxis = "y2",
    customdata = ~price,
    hovertemplate = paste(
      "Date: %{x}<br>",
      "Bitcoin Price: $%{customdata:.2f}<extra></extra>"
    )
  ) %>%
  layout(
    title = "US Debt vs. Bitcoin Price Over Time",
    margin = list(r = 80),  # more space for right y-axis labels
    xaxis = list(
      title = "Date",
      range = c(min(combined$observation_date), today),
      fixedrange = TRUE     # lock the range so no panning/scrolling
    ),
    yaxis = list(
      title = "US Debt (in Trillion USD)",
      titlefont = list(color = "blue"),
      tickfont = list(color = "blue"),
      tickformat = ",.0f"
    ),
    yaxis2 = list(
      title = "Bitcoin Price (USD)",
      titlefont = list(color = "orange"),
      tickfont = list(color = "orange"),
      overlaying = "y",
      side = "right",
      tickvals = seq(min(combined$price_scaled), max(combined$price_scaled), length.out = 6),
      ticktext = paste0("$", formatC(seq(min_price, max_price, length.out = 6), format = "f", digits = 0, big.mark = ","))
    ),
    legend = list(x = 0.01, y = 0.99)
  )