set preserve_insertion_order = true;

create or replace table day01_data as
  select operation,
    if(operation[1] == 'L', -1, 1) as multiplier,
    operation[2:]::int as add
  from read_csv(
    'inputs/01/input.txt',
    header = false,
    columns = { 'operation': 'VARCHAR' }
  );

create or replace table day01_test as
  select operation,
    if(operation[1] == 'L', -1, 1) as multiplier,
    operation[2:]::int as add
  from read_csv(
    'inputs/01/test.txt',
    header = false,
    columns = { 'operation': 'VARCHAR' }
  );

create or replace table day01_data_states as
  select
    rowid,
    operation,
    multiplier,
    add as raw_add,
    floor(add / 100)::int as turns,
    add - (turns * 100) as clean_add,
    50 + SUM(clean_add * multiplier) OVER (
      ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) as state
  from day01_data
;

with
states as (
  select
    lag(abs(state + 100) % 100, 1, 50) over () as previous,
    operation,
    turns,
    abs(state + 100) % 100 as state
  from day01_data_states
)
select count(1) as part1
from states
where state == 0;

--------------

create or replace table day01_part2 as
select
  lag(state, 1, 50) over () as raw_previous,
  state as raw_current,
  operation,
  raw_previous % 100 == 0 as went_from_zero,
  floor(raw_previous / 100)::int as prev_hundred,
  floor(raw_current / 100)::int as current_hundred,
  if(not went_from_zero and prev_hundred != current_hundred, 1, NULL) as hundred_change,
  if((state + 100) % 100 == 0, 1, NULL) as exact_0,
  turns,
  turns + coalesce(exact_0, hundred_change, 0) as total_zero_clicks
from day01_data_states;

select
  sum(total_zero_clicks) as part2
from day01_part2;

