# -*- coding: utf-8 -*-
from __future__ import annotations

import csv
import datetime
import logging
import os
import uuid

from celery.result import AsyncResult
from django import db
from django.utils.timezone import get_current_timezone

from hotpocket_backend.apps.ui.services.workflows import ImportSaveWorkflow
from hotpocket_backend.apps.ui.tasks import import_from_pocket
from hotpocket_common.uuid import uuid7_from_timestamp
from hotpocket_soa.services import SavesService

LOGGER = logging.getLogger(__name__)


class UIImportsService:
    def import_from_pocket(self,
                           *,
                           job: str,
                           account_uuid: uuid.UUID,
                           csv_path: str,
                           ) -> list[tuple[uuid.UUID, uuid.UUID]]:
        LOGGER.info(
            'Starting import job: job=`%s` account_uuid=`%s`',
            job,
            account_uuid,
            extra={
                'job': job,
            },
        )

        result = []
        with db.transaction.atomic():
            try:
                with open(csv_path, 'r', encoding='utf-8') as csv_file:
                    csv_reader = csv.DictReader(
                        csv_file,
                        fieldnames=['title', 'url', 'time_added', 'tags', 'status'],
                    )

                    current_timezone = get_current_timezone()

                    is_header = False
                    for row_number, row in enumerate(csv_reader, start=1):
                        if is_header is False:
                            is_header = True
                            continue

                        timestamp = int(row['time_added'])

                        try:
                            save, association = ImportSaveWorkflow().run(
                                account_uuid=account_uuid,
                                url=row['url'],
                                title=row['title'],
                                pk=uuid7_from_timestamp(timestamp),
                                created_at=datetime.datetime.fromtimestamp(
                                    timestamp, tz=current_timezone,
                                ),
                            )
                        except SavesService.Invalid as exception:
                            LOGGER.error(
                                'Import error: row_number=`%d` url=`%s` exception=`%s`',
                                row_number,
                                row['url'],
                                exception,
                                exc_info=exception,
                                extra={
                                    'job': job,
                                },
                            )
                            continue

                        result.append((save.pk, association.pk))
            finally:
                os.unlink(csv_path)

        return result

    def schedule_import_from_pocket(self,
                                    *,
                                    account_uuid: uuid.UUID,
                                    csv_path: str,
                                    ) -> AsyncResult:
        return import_from_pocket.apply_async(
            kwargs={
                'job': str(uuid.uuid4()),
                'account_uuid': account_uuid,
                'csv_path': csv_path,
            },
        )
