#!/usr/bin/env perl
use strict;
use warnings;

open(my $fh, '<', 'input') or die "$!";
# slurp
my $content;
{
    local $/;
    $content = <$fh>;
}

my @recs = split("\n\n", $content);
my $n = 0;
my %required = (
    byr => sub { $_[0] =~ /^\d\d\d\d$/ && $_[0] >= 1920 && $_[0] <= 2002 },
    iyr  => sub { $_[0] =~ /^\d\d\d\d$/ && $_[0] >= 2010 && $_[0] <= 2020 },
    eyr  => sub { $_[0] =~ /^\d\d\d\d$/ && $_[0] >= 2020 && $_[0] <= 2030 },
    hgt  => sub {
        my $v = $_[0];
        if ($v =~ /^(\d\d+)(cm|in)$/) {
            if ($2 eq 'cm') { 
                return ($1 >= 150 && $1 <= 193);
            } else {
                return ($1 >= 59 && $1 <= 76);
            }
        } else {
            return 0;
        }
    },
    hcl  => sub { $_[0] =~ /^#[0-9a-f]{6}$/ },
    ecl  => sub { $_[0] =~ /^(amb|blu|brn|gry|grn|hzl|oth)$/ },
    pid => sub { $_[0] =~ /^\d{9}$/ },
);
REC:
for my $r (@recs) {
	my @fields = split(/\s+/, $r);

        # parse the fields, validate as you go
        my %has;
        for my $f (@fields) {
            my ($k, $v) = split(':', $f);
            $has{$k} = $v;
            if (!exists $required{$k}) {
                next if $k eq 'cid'; #ok

                print "unknown key: $k\n";
                next REC;
            }
            if (!$required{$k}->($v)) {
                # print "bad key/val: $k:$v\n";
                next REC;
            }
        }

        # check they all exist
	for my $req (keys %required) {
		next REC if !exists $has{$req};
	}
	$n++;
}
print "$n\n";
