"""Shared eligibility for current owner positions; never changes saved records."""
from datetime import date

OPEN_JOB_STAGES = frozenset(('new', 'site_visit', 'accepted', 'scheduled', 'in_progress', 'on_hold'))


def calendar_date(value):
    try:
        return value if len(value) == 10 and date.fromisoformat(value).isoformat() == value else None
    except (ValueError, TypeError):
        return None


def open_job(status, archived):
    return status in OPEN_JOB_STAGES and not archived


def open_quote_state(quote, job_status, job_archived, observation_day):
    """Expiry is inclusive in London. Blank is undated; malformed is unknown."""
    if not quote['current'] or quote['status'] not in ('draft', 'shared') or not open_job(job_status, job_archived):
        return 'excluded'
    expiry = quote.get('valid_until') or ''
    if expiry and not calendar_date(expiry):
        return 'unknown_expiry'
    return 'included' if not expiry or expiry >= observation_day else 'excluded'
