package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
//	"slices"
	"strconv"
	"strings"
)

func rmIndex(s []int, i int) []int {
  result := make([]int, 0)
  result = append(result, s[:i]...)
  result = append(result, s[i+1:]...)
  return result
}

func isSorted(s []int) bool {
  n := len(s)
  asc := true
  desc := true
  for i := 1; i < n; i++ {
    if s[i-1] < s[i] {
      desc = false
    }
    if s[i-1] > s[i] {
      asc = false
    }
  }
  if asc || desc {
    return true
  } else {
    return false
  }
}

func isSafe(r []int) bool {
  if isSorted(r) {
    for i := range r {
      if i < len(r)-1 {
        if math.Abs(float64(r[i]-r[i+1])) < 1 || math.Abs(float64(r[i]-r[i+1])) > 3 {
          return false
        }
      }
    }
    return true
  } else {
    return false
  }
}

func main() {
  file, err := os.Open("input")
  if err != nil {
    panic(err)
  }
  defer file.Close()
  scanner := bufio.NewScanner(file)
  reports := [][]int{}
  for scanner.Scan() {
    line := scanner.Text()
    parts := strings.Fields(line)
    levels := []int{}
    for i := range parts {
      level,_ := strconv.Atoi(parts[i])
      levels = append(levels, level)
    }
    reports = append(reports, levels)
  }
  safeCount := 0
  dampSafeCount := 0
  for i := range reports {
    if isSafe(reports[i]) {
      safeCount++
    } else {
      for j := range reports[i] {
        dampenedReport := rmIndex(reports[i], j)
        if isSafe(dampenedReport) {
          dampSafeCount++
          break
        }
      }
    }
  }
  fmt.Println("Safe Reports: ", safeCount)
  fmt.Println("Dampened Safe Reports: ", dampSafeCount)
  fmt.Println("Total Safe Reports: ", safeCount+dampSafeCount)
//  sorted := 0
//  unsorted := 0
//  sortedUnsafe := 0
//  for i := range reports {
//    if ! isSorted(reports[i]) {
//      unsorted++
//      continue
//    } else {
//      sorted++
//      for j := range reports[i] {
//        if j < len(reports[i])-1 {
//          if math.Abs(float64(reports[i][j]-reports[i][j+1])) < 1 || math.Abs(float64(reports[i][j]-reports[i][j+1])) > 3 {
//            fmt.Println(reports[i])
//            sortedUnsafe++
//            break
//          }
//        }
//      }
//    }
//  }
//  fmt.Println(len(reports))
//  fmt.Println("sorted lines: ", sorted)
//  fmt.Println("unsorted lines: ", unsorted)
//  fmt.Println("sortedUnsafe lines: ", sortedUnsafe)
//  fmt.Println("safeCount math : ", len(reports) - unsorted - sortedUnsafe)
}
