library(readr) # For reading CSV files
library(dplyr) # For data manipulation
library(tidyverse) # For data manipulation
library(sf) # For handling spatial data
library(caret) # For train/test split and preprocessing

path <- "own_path/dataset/"

df_environment <- read_csv(paste0(path, "RegionalEnvironment.csv"), locale = locale(encoding = "CP932"))
gdf_hausing <- st_read(paste0(path, "Hausing.geojson"))
gdf_polygon <- st_read(paste0(path, "Polygons.geojson"))

get_key_code <- function(point_list, mesh_data) {
  key_code_list <- c()
  for (i in seq_along(point_list)) {
    point <- point_list[i, ]
    key_code <- mesh_data[t(st_contains(mesh_data, point))[[1]], ]$KEY_CODE[1]
    key_code_list <- c(key_code_list, key_code)
  }
  return(key_code_list)
}

gdf_hausing <- st_transform(gdf_hausing, crs = st_crs(3100))
gdf_polygon <- st_transform(gdf_polygon, crs = st_crs(3100))
gdf_hausing$KEY_CODE <- get_key_code(gdf_hausing$geometry, gdf_polygon)

df <- gdf_hausing %>%
  left_join(df_environment, by = "KEY_CODE") %>%
  filter(利用現況 == "住宅") %>%
  drop_na() %>%
  st_drop_geometry()

features <- c('地積', '間口比率', '建蔽率', '容積率', 'ガス有無', '下水有無', '前面道路の幅員', '駅までの距離',
              '災害危険区域', '津波浸水想定区域', '小学校までの距離', '中学校までの距離', '警察署までの距離', 'バス停までの距離', '人口')

X <- df[, features]
Y <- df$公示価格 / 10000

set.seed(0)
split <- createDataPartition(Y, p = .9, list = FALSE)
train_X <- X[split, ]
test_X <- X[-split, ] %>% select(-公示価格)
test_Y <- X[-split, ]$公示価格

regr <- lm(公示価格 ~ ., data=train_X)
print(summary(regr))

pred_Y = predict(regr, test_X)
mse <- mean((test_Y - pred_Y)^2)
r2 <- 1 - sum((test_Y - pred_Y)^2) / 
  sum((test_Y - mean(test_Y))^2)

print(paste("MSE :", mse))
print(paste("R2", r2))

plot(test_Y, pred_Y)
abline(coef = c(0,1))