create or replace table day07_data as
    select row_number() over () as line, column0
  from read_csv('inputs/07/input.txt', header=false, delim='\n');
create or replace table day07_test as
    select row_number() over () as line, column0
  from read_csv('inputs/07/test.txt', header=false, delim='\n');

create or replace table day07_input as
  select
    line as y,
    if(c = 'S', x, null) as starter,
    if(c = '^', x, null) as splitter
  from day07_test,
    unnest(split(column0, '')) with ordinality as u(c, x)
  where c != '.'
;

with recursive seq(y, x) as (
  select
    y,
    starter as x
  from day07_input
  where y = 1

  union all

  select distinct
    s.y + 1 as y,
    if(m.splitter = s.x, unnest([s.x + 1, s.x - 1]), s.x) as x
  from seq as s
  left join day07_input as m
    on m.y = s.y + 1 and m.splitter = s.x
  where s.y <= (select max(y) from day07_input)
)
select count(1) as part1
from seq s
inner join day07_input m on s.y = m.y - 1 and s.x = m.splitter;

with recursive seq(y, x) as (
  select
    y,
    starter as x,
    0 as split
  from day07_input
  where y = 1

  union all

  select
    s.y + 1 as y,
    if(m.splitter = s.x, unnest([s.x + 1, s.x - 1]), s.x) as x,
    if(m.splitter = s.x, 1, 0) as split
  from seq as s
  left join day07_input as m
    on m.y = s.y + 1 and m.splitter = s.x
  where s.y <= (select max(y) from day07_input)
)
select sum(split) as part2
from seq s;
