"""Anniversary feed and daily notification worker (Mauritius time)."""
from datetime import date, datetime, timezone, timedelta
from email.message import EmailMessage
import os
import smtplib
import ssl
import time
from db import DBConnection

MAURITIUS = timezone(timedelta(hours=4))


def initialize_celebrations(conn):
    conn.execute('''CREATE TABLE IF NOT EXISTS celebration_settings (
        id INTEGER PRIMARY KEY, recipient TEXT NOT NULL DEFAULT '', send_time TEXT NOT NULL DEFAULT '08:00',
        enabled INTEGER NOT NULL DEFAULT 0)''')
    conn.execute('INSERT INTO celebration_settings(id) VALUES(1) ON CONFLICT(id) DO NOTHING')
    conn.execute("UPDATE celebration_settings SET recipient='Sophie@PlanetProduction.fr' WHERE id=1 AND recipient='' AND enabled=0")
    conn.execute('''CREATE TABLE IF NOT EXISTS celebration_deliveries (
        send_date TEXT PRIMARY KEY, status TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '',
        updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)''')
    conn.commit()


def parse_day(value):
    if not value:
        return None
    return value if isinstance(value,date) else date.fromisoformat(str(value))


def events_today(conn, today, public=False):
    events = []
    people = conn.execute('''SELECT id,full_name,team,start_date,birth_date,birthday_public,
        birthday_show_age,birthday_email,anniversary_public FROM users WHERE active=TRUE ORDER BY full_name''').fetchall()
    for person in people:
        for kind,field in [('birthday','birth_date'),('anniversary','start_date')]:
            try:
                origin = parse_day(person[field])
            except ValueError:
                continue
            if not origin or origin>=today or (origin.month,origin.day)!=(today.month,today.day):
                continue
            if kind == 'birthday' and not person['birthday_public' if public else 'birthday_email']:
                continue
            if kind == 'anniversary' and public and not person['anniversary_public']:
                continue
            years = today.year-origin.year
            events.append(dict(name=person['full_name'],team=person['team'],kind=kind,
                               years=years if kind=='anniversary' else None,
                               milestone=kind=='anniversary' and years in {1,5,10,15,20,25,30}))
    return events


def digest(events,today):
    lines = [f'Anniversaires du {today:%d/%m/%Y} — Planète Production', '']
    if not events:
        lines.append('Aucun événement à annoncer aujourd’hui.')
    for event in events:
        if event['kind']=='birthday':
            text = 'anniversaire' + (f" — {event['years']} ans" if event['years'] is not None else '')
        else:
            text = f"{event['years']} an(s) dans la société" + (' — étape à célébrer' if event['milestone'] else '')
        lines.append(f"• {event['name']} ({event['team'] or 'équipe non renseignée'}) : {text}")
    lines += ['', 'Les coordonnées bancaires et les dates de naissance complètes ne figurent pas dans ce récapitulatif.']
    return '\n'.join(lines)


def send_daily_digest():
    conn = DBConnection()
    try:
        now = datetime.now(MAURITIUS)
        config = conn.execute('SELECT * FROM celebration_settings WHERE id=1').fetchone()
        if not config or not config['enabled'] or not config['recipient'] or now.strftime('%H:%M')<config['send_time']:
            return
        events = events_today(conn,now.date())
        if not events:
            return
        host, sender = os.getenv('RH_SMTP_HOST'),os.getenv('RH_SMTP_FROM')
        if not host or not sender:
            return
        cur = conn.execute("INSERT INTO celebration_deliveries(send_date,status) VALUES(?,'sending') ON CONFLICT(send_date) DO NOTHING", (now.date().isoformat(),))
        claimed = cur.cursor.rowcount
        conn.commit()
        if not claimed:
            return
        try:
            message = EmailMessage()
            message['Subject'] = f'Planète RH — anniversaires du {now:%d/%m/%Y}'
            message['From'],message['To'] = sender,config['recipient']
            message.set_content(digest(events,now.date()))
            mode = os.getenv('RH_SMTP_SECURITY','starttls')
            if mode not in {'ssl','starttls'}:
                raise ValueError('TLS required')
            client = smtplib.SMTP_SSL if mode=='ssl' else smtplib.SMTP
            port = int(os.getenv('RH_SMTP_PORT','465' if mode=='ssl' else '587'))
            with client(host,port,timeout=20) as smtp:
                if mode=='starttls':
                    smtp.starttls(context=ssl.create_default_context())
                if os.getenv('RH_SMTP_USER'):
                    smtp.login(os.getenv('RH_SMTP_USER'),os.getenv('RH_SMTP_PASSWORD',''))
                smtp.send_message(message)
            status,detail = 'sent',f'{len(events)} événement(s)'
        except Exception as error:
            status,detail = 'failed',type(error).__name__
        conn.execute('UPDATE celebration_deliveries SET status=?,detail=?,updated_at=CURRENT_TIMESTAMP WHERE send_date=?',
                     (status,detail,now.date().isoformat()))
        conn.commit()
    finally:
        conn.close()


def run_worker():
    while True:
        try:
            send_daily_digest()
        except Exception:
            # Retry configuration/database availability on the next tick; never log secrets.
            pass
        time.sleep(60)


if __name__=='__main__':
    run_worker()
