import datetime

from csirtmu.beta_temporal.external_services.alpha.client import AlphaClient
from csirtmu.beta_temporal.external_services.alpha.structs import AccountingRecord


async def get_culprit_based_on_ip(
    ip: str | None, timestamp: str | None, client: AlphaClient
) -> AccountingRecord | None:
    if not ip or not timestamp:
        return None
    time = datetime.datetime.fromisoformat(timestamp)
    five_minutes = datetime.timedelta(minutes=5)
    data = await client.get_user_for_ip_and_timestamp(ip, time - five_minutes, time + five_minutes)
    if not data:
        return None
    latest: AccountingRecord | None = None
    for record in data.data:
        if (
            (
                (record.framed_ip_address is not None and record.framed_ip_address.exploded == ip)
                or (record.framed_ip_v6_address is not None and record.framed_ip_v6_address.exploded == ip)
            )
            and record.start_time <= time
            and (latest is None or latest.start_time < record.start_time)
        ):
            latest = record
    return latest
