from __future__ import annotations

import asyncio
import fcntl
import json
import logging
import os
import re
from pathlib import Path

from .adapters import SyncAdapter
from .config import Settings
from .schemas import utcnow
from .storage import Store

logger = logging.getLogger("bi_sync_worker")


class WorkerRunner:
    def __init__(self, store: Store, adapter: SyncAdapter, settings: Settings):
        self.store, self.adapter, self.settings = store, adapter, settings

    async def serve(self) -> None:
        while True:
            try:
                worked = await self.run_once()
            except asyncio.CancelledError:
                raise
            except Exception:
                logger.exception("Worker iteration failed")
                worked = False
            if not worked:
                await asyncio.sleep(0.25)

    async def run_once(self) -> bool:
        run_id = self.store.next_queued()
        if run_id is None:
            return False
        lock_path = self.settings.lock_path
        try:
            lock_path.parent.mkdir(parents=True, exist_ok=True)
            lock_file = lock_path.open("a+")
        except OSError:
            logger.exception("Unable to access the shared sync lock; leaving run queued: run_id=%s", run_id)
            self.store.requeue(run_id)
            return False
        with lock_file:
            try:
                fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except BlockingIOError:
                self.store.requeue(run_id)
                return False
            try:
                connection, tables = self.store.queued_payload(run_id)
                log_path = self.settings.log_dir / f"{run_id}.jsonl"
                log_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
                os.chmod(log_path.parent, 0o700)
                with log_path.open("a", encoding="utf-8") as log:
                    os.chmod(log_path, 0o600)
                    log.write(json.dumps({"event": "run_started", "run_id": run_id, "at": utcnow()}) + "\n")
                for table in tables:
                    self.store.table_update(run_id, table, status="running", started_at=utcnow(), error_message=None)
                    def on_event(event: dict) -> None:
                        if event.get("name") != table:
                            return
                        event_type = event.get("event")
                        if event_type == "table_started":
                            self.store.table_update(run_id, table, status="running", started_at=utcnow())
                        elif event_type in {"table_progress", "table_completed"}:
                            rows = event.get("rows_imported")
                            previous = event.get("previous_rows")
                            if rows is not None and (not isinstance(rows, int) or isinstance(rows, bool) or rows < 0):
                                return
                            if previous is not None and (not isinstance(previous, int) or isinstance(previous, bool) or previous < 0):
                                return
                            backup = event.get("backup_table")
                            if backup is not None and (not isinstance(backup, str) or re.fullmatch(r"[a-z_][a-z0-9_]*", backup) is None):
                                return
                            self.store.table_update(
                                run_id, table,
                                rows_imported=event.get("rows_imported"),
                                previous_rows=event.get("previous_rows"),
                                backup_table=event.get("backup_table"),
                            )
                        elif event_type == "table_failed":
                            self.store.table_update(run_id, table, error_message=str(event.get("error_message", "Sync script reported failure"))[:1000])

                    try:
                        result = await self.adapter.run_table(run_id, connection, table, log_path, on_event)
                    except asyncio.CancelledError:
                        raise
                    except Exception:
                        logger.exception("Adapter failed with an uncertain process result: run_id=%s table=%s", run_id, table)
                        self.store.mark_uncertain(run_id, "El resultado del sincronizador es incierto; requiere conciliación manual.")
                        return True
                    if result.uncertain:
                        error = "El sincronizador no confirmó si publicó la tabla; requiere conciliación manual."
                        self.store.table_update(run_id, table, error_message=error)
                        self.store.mark_uncertain(run_id, error)
                        return True
                    if result.returncode != 0 or not result.saw_publication:
                        error = "La sincronización no confirmó la publicación de la tabla."
                        self.store.table_update(run_id, table, status="failed", finished_at=utcnow(), error_message=error)
                        self.store.finish(run_id, "failed", error)
                        return True
                    # Adapters must record the table_completed JSONL event before claiming publication.
                    events = self._read_events(log_path)
                    completed = next((event for event in reversed(events) if event.get("event") == "table_completed" and event.get("name") == table), {})
                    if completed.get("published") is not True:
                        error = "La sincronización terminó sin confirmar EXCHANGE TABLES."
                        self.store.table_update(run_id, table, status="failed", finished_at=utcnow(), error_message=error)
                        self.store.finish(run_id, "failed", error)
                        return True
                    if not isinstance(completed.get("rows_imported"), int) or isinstance(completed.get("rows_imported"), bool) or completed["rows_imported"] < 0:
                        error = "La sincronización terminó sin una cantidad válida de filas publicadas."
                        self.store.mark_uncertain(run_id, error)
                        self.store.table_update(run_id, table, error_message=error)
                        return True
                    previous = completed.get("previous_rows")
                    backup = completed.get("backup_table")
                    if (previous is not None and (not isinstance(previous, int) or isinstance(previous, bool) or previous < 0)) or (
                        backup is not None and (not isinstance(backup, str) or re.fullmatch(r"[a-z_][a-z0-9_]*", backup) is None)
                    ):
                        error = "El sincronizador devolvió metadatos de tabla no válidos; requiere conciliación manual."
                        self.store.mark_uncertain(run_id, error)
                        self.store.table_update(run_id, table, error_message=error)
                        return True
                    self.store.table_update(run_id, table, status="completed", rows_imported=completed.get("rows_imported"),
                                            previous_rows=completed.get("previous_rows"), backup_table=completed.get("backup_table"),
                                            finished_at=utcnow(), error_message=None)
                self.store.finish(run_id, "completed")
                return True
            except asyncio.CancelledError:
                self.store.mark_uncertain(run_id, "El worker se detuvo durante una ejecución; requiere conciliación manual.")
                raise
            except Exception:
                logger.exception("Run state is uncertain after internal worker error: run_id=%s", run_id)
                self.store.mark_uncertain(run_id, "Error interno durante la ejecución; requiere conciliación manual.")
                return True
            finally:
                fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)

    @staticmethod
    def _read_events(path: Path) -> list[dict]:
        events = []
        with path.open(encoding="utf-8") as stream:
            for line in stream:
                try:
                    event = json.loads(line)
                except (json.JSONDecodeError, ValueError):
                    continue
                if isinstance(event, dict):
                    events.append(event)
        return events

