from datetime import timedelta, date

from db import get_session
import re
from sqlalchemy import text


def main():
    db = next(get_session())
    q = db.execute(text("SELECT * FROM dbo.Forderungen_Kommentar_Rohdaten"))

    for row in q.fetchall():
        for i, r in enumerate(row.Kommentar.split("\n"), 1):
            comment_date = row.Timestamp + timedelta(minutes=i)
            comment_user = row.Benutzer_ID
            r = r.replace("'", "")
            d, u = get_date_and_user_from_comment(r)
            db.execute(
                text(
                    "INSERT INTO dbo.Forderungen_Kommentar "
                    f"VALUES ('{row.Client_DB}', '{row.Beleg_Nr}', '{comment_date}', '{comment_user}', '{r}')"
                )
            )

    db.commit()


def get_date_and_user_from_comment(r: str) -> tuple[date, str]:
    m = re.search(r"(\d\d\.\d\d?)\.?[\/\s](\w+)", r)
    if m:
        date_split = m[1].split(".")
        return date(2026, date_split[1], date_split[0]), m[2]

    if r.startswith("EWB"):
        return None, "mde"

    az = re.search(r"^AZ\:?\s(\d+\/\d+)", r)
    if az:
        return None, "mde"
    return None, "mde"


if __name__ == "__main__":
    main()
