import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

from datetime import datetime

from peewee import JOIN

from hamstertools.db import (
    HamsterCategory,
    HamsterActivity,
    HamsterFact,
    HamsterFactKimaiImport,
)
from hamstertools.kimai import KimaiAPI, Timesheet, Project, Activity

api = KimaiAPI()

DATE_FROM = "2023-10-01"
DATE_TO = "2023-11-01"
SEARCH = "auto"

facts = (
    HamsterFact.select(HamsterFact, HamsterActivity, HamsterCategory)
    .join(HamsterActivity, JOIN.LEFT_OUTER)
    .join(HamsterCategory, JOIN.LEFT_OUTER)
    .where(
        (HamsterFact.start_time > datetime.strptime(DATE_FROM, "%Y-%m-%d"))
        & (HamsterFact.start_time < datetime.strptime(DATE_TO, "%Y-%m-%d"))
        & HamsterCategory.name.contains(SEARCH)
    )
)

has_errors = False

# check data
for f in facts:
    mappings = f.activity.mappings
    if len(mappings) == 0:
        print(
            f"fact {f.id}: @{f.activity.category.id} {f.activity.category.name} » @{f.activity.id} {f.activity.name} has no mapping"
        )
        has_errors = True
        continue
    if len(mappings) > 1:
        print(
            f"fact {f.id}: activity @{f.activity.id} {f.activity.name} has multiple mappings"
        )
        has_errors = True
        continue
    if (
        mappings[0].kimai_activity.project is None
        and not mappings[0].kimai_project.allow_global_activities
    ):
        print(
            f"fact {f.id}: project @{mappings[0].kimai_project.id} {mappings[0].kimai_project.name} does not allow global activity {mappings[0].kimai_activity}"
        )
        has_errors = True
        continue
    if f.imports.count() > 0:
        print(
            f"fact {f.id}: activity @{f.activity.id} {f.activity.name} was already imported {f.imports.count()} time(s)"
        )
        has_errors = True
        continue


# if has_errors:
#     sys.exit(1)

# upload data
for f in facts:
    try:
        mapping = f.activity.mappings[0]
    except IndexError:
        print(
            f"no mapping, skipping {f.id} ({f.activity.category.name} » {f.activity.name})"
        )
        continue

    if f.imports.count() > 0:
        print(
            f"already imported, skipping {f.id} ({f.activity.category.name} » {f.activity.name})"
        )
        continue

    t = Timesheet(
        api,
        activity=mapping.kimai_activity,
        project=mapping.kimai_project,
        begin=f.start_time,
        end=f.end_time,
        description=f.description if f.description != "" else mapping.kimai_description,
        # tags=f.tags if f.tags != '' else mapping.kimai_tags
    )
    r = t.upload().json()
    if r.get("code", 200) != 200:
        print(r)
        print(f"{f.id} ({f.activity.category.name} » {f.activity.name})")
        from pdb import set_trace

        set_trace()

    else:
        HamsterFactKimaiImport.create(hamster_fact=f, kimai_id=r["id"]).save()
        print(f'Created Kimai timesheet {r["id"]}')