<gh_stars>0
#!/usr/bin/env python

import sys
sys.path.append('..')
from libs.helpers import get_input
import re


mandatory = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']
optional = ['cid']
valideyecolors = ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']


def parsepassports(lines):
    pps = []
    pp = []
    for l in lines:
        if l == '' and pp:
            pps.append(passdict(pp))
            pp = []
        else:
            pp.append(l)
    pps.append(passdict(pp))
    return pps


def passdict(lines):
    line = ' '.join(lines)
    lines = line.split()
    return {c[0]: c[1] for c in [l.split(':') for l in lines]}


def scan(passport):
    return all(m in passport for m in mandatory)


def scanstrict(p):
    if not scan(p):
        return False
    if not intrange(p['byr'], 1920, 2002):
        return False
    if not intrange(p['iyr'], 2010, 2020):
        return False
    if not intrange(p['eyr'], 2020, 2030):
        return False
    hgt = p['hgt']
    if hgt.endswith('cm'):
        hgti = int(hgt.replace('cm', ''))
        if hgti < 150 or hgti > 193:
            return False
    elif hgt.endswith('in'):
        hgti = int(hgt.replace('in', ''))
        if hgti < 59 or hgti > 76:
            return False
    elif not hgt.endswith('cm') and not hgt.endswith('in'):
        return False
    hcl = p['hcl']
    if not re.search('^#[0-9a-f]{6}$', hcl):
        return False
    if not p['ecl'] in valideyecolors:
        return False
    pid = p['pid']
    if not re.search('^\d{9}$', pid):
        return False
    return True


def intrange(v, mi, ma):
    if not re.search('^\d{4}$', v):
        return False
    try:
        v = int(v)
        return mi <= v <= ma
    except Exception:
        return False


if __name__ == '__main__':
    lines = get_input('input.txt')
    pps = parsepassports(lines)
    valid = sum(1 if scan(p) else 0 for p in pps)
    print(valid)
    valid = sum(1 if scanstrict(p) else 0 for p in pps)
    print(valid)
