"""Base candidate and checksum checks; no official assignment lookup."""
from datetime import date
import re

MONTH = {1:'A',2:'B',3:'C',4:'D',5:'E',6:'H',
         7:'L',8:'M',9:'P',10:'R',11:'S',12:'T'}

def _consonants(s): return [c for c in s if c not in 'AEIOU']
def _vowels(s):     return [c for c in s if c in 'AEIOU']

def _name_code(s, is_first_name=False):
    if not isinstance(s, str) or not re.fullmatch(r"[A-Za-z '\-]+", s):
        raise ValueError('Use the recorded ASCII name; no transliteration is inferred')
    s = ''.join(ch for ch in s.upper() if 'A' <= ch <= 'Z')
    if not s:
        raise ValueError('Name must contain letters')
    cons, vow = _consonants(s), _vowels(s)
    if is_first_name and len(cons) >= 4:        # the one special case
        cons = [cons[0], cons[2], cons[3]]
    code = (cons + vow + ['X', 'X', 'X'])[:3]
    return ''.join(code)

# Odd/even position tables — also public, also not a secret.
ODD = {**{str(i): v for i, v in enumerate(
        [1,0,5,7,9,13,15,17,19,21])},
       **dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        [1,0,5,7,9,13,15,17,19,21,2,4,18,20,11,3,6,8,12,14,16,10,22,25,24,23]))}
EVEN = {**{str(i): i for i in range(10)},
        **{c: i for i, c in enumerate("ABCDEFGHIJKLMNOPQRSTUVWXYZ")}}

def codice_fiscale(surname, name, year, month, day, sex, belfiore):
    """Compute a base candidate, not an officially assigned identifier."""
    if any(type(v) is not int for v in (year, month, day)):
        raise ValueError('Date fields must be integers')
    date(year, month, day)
    if not isinstance(sex, str) or sex.upper() not in {'M', 'F'}:
        raise ValueError('Recorded sex code must be M or F')
    if not isinstance(belfiore, str) or not re.fullmatch(r'[A-Za-z][0-9]{3}', belfiore):
        raise ValueError('Expected one letter and three digits for a base place code')
    cf  = _name_code(surname)
    cf += _name_code(name, is_first_name=True)
    cf += f"{year % 100:02d}"
    cf += MONTH[month]
    cf += f"{day + (40 if sex.upper() == 'F' else 0):02d}"   # women: day + 40
    cf += belfiore.upper()
    total = sum((ODD if i % 2 == 0 else EVEN)[ch] for i, ch in enumerate(cf))
    return cf + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[total % 26]

def checksum_valid(value):
    """Check alphanumeric format/checksum only, never registry assignment."""
    if not isinstance(value, str):
        return False
    value = value.upper()
    pattern = r'[A-Z]{6}[0-9LMNPQRSTUV]{2}[ABCDEHLMPRST][0-9LMNPQRSTUV]{2}[A-Z][0-9LMNPQRSTUV]{3}[A-Z]'
    if not re.fullmatch(pattern, value):
        return False
    total = sum((ODD if i % 2 == 0 else EVEN)[ch]
                for i, ch in enumerate(value[:15]))
    return value[-1] == 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[total % 26]

# Synthetic calculation fixture; no registry lookup or identity claim.
assert codice_fiscale('Rossi', 'Mario', 1985, 12, 10, 'M', 'A562') == 'RSSMRA85T10A562S'
assert checksum_valid('RSSMRA85T10A562S')
assert not checksum_valid('RSSMRA85T10A562A')
assert not checksum_valid('not-an-identifier')
for bad in ((1985, 2, 30, 'M', 'A562'), (1985, 12, 10, 'X', 'A562'),
            (1985, 12, 10, 'M', 'INVALID')):
    try:
        codice_fiscale('Rossi', 'Mario', *bad)
    except ValueError:
        continue
    raise AssertionError('Invalid input accepted')
