from __future__ import annotations

import asyncio
import json
import logging
import os
import signal
from dataclasses import dataclass
from pathlib import Path
from typing import AsyncIterator, Callable, Optional, Protocol

from .config import Settings

logger = logging.getLogger("bi_sync_worker")


@dataclass
class AdapterResult:
    returncode: int
    saw_publication: bool
    uncertain: bool = False


class SyncAdapter(Protocol):
    async def run_table(self, run_id: str, connection: str, table: str, log_path: Path,
                        on_event: Callable[[dict], None]) -> AdapterResult: ...


async def _lines(stream: asyncio.StreamReader) -> AsyncIterator[str]:
    while line := await stream.readline():
        yield line.decode("utf-8", errors="replace").rstrip("\r\n")


def _safe_line(line: str, token: str) -> str:
    if token:
        line = line.replace(token, "[REDACTED]")
    import re
    return re.sub(r"(?i)(password|passwd|token|secret|authorization)(\s*[=:]\s*)([^\s,;]+)", r"\1\2[REDACTED]", line)


class SimulatedAdapter:
    def __init__(self, delay: float):
        self.delay = delay

    async def run_table(self, run_id: str, connection: str, table: str, log_path: Path,
                        on_event: Callable[[dict], None]) -> AdapterResult:
        await asyncio.sleep(self.delay)
        on_event({"event": "table_started", "name": table})
        on_event({"event": "table_completed", "name": table, "rows_imported": 0,
                  "previous_rows": 0, "backup_table": None, "published": True, "simulated": True})
        with log_path.open("a", encoding="utf-8") as log:
            log.write(json.dumps({"event": "table_started", "name": table}) + "\n")
            log.write(json.dumps({"event": "table_completed", "name": table, "rows_imported": 0,
                                  "previous_rows": 0, "backup_table": None, "published": True,
                                  "simulated": True}) + "\n")
        logger.info("Simulated table run completed: run_id=%s table=%s", run_id, table)
        return AdapterResult(returncode=0, saw_publication=True)


class PodmanAdapter:
    """Fixed command adapter; values from HTTP never become executable options."""
    def __init__(self, settings: Settings):
        self.settings = settings

    def argv(self, table: str) -> list[str]:
        command = [self.settings.podman_bin]
        if self.settings.podman_remote:
            command.append("--remote")
        return command + [
            "run", "--rm", "--network", self.settings.podman_network,
            "--volume", f"{self.settings.sync_directory}:{self.settings.sync_directory}:Z",
            "--env-file", self.settings.podman_env_file,
            "--entrypoint", "python3", self.settings.podman_image,
            self.settings.sync_script, "--view", table,
        ]

    async def run_table(self, run_id: str, connection: str, table: str, log_path: Path,
                        on_event: Callable[[dict], None]) -> AdapterResult:
        proc = await asyncio.create_subprocess_exec(
            *self.argv(table), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
            start_new_session=True, limit=65536,
        )
        saw_publication = False
        last_safe_error: Optional[str] = None
        saw_explicit_failure = False

        async def consume() -> None:
            nonlocal saw_publication, last_safe_error, saw_explicit_failure
            assert proc.stdout is not None
            async for raw in _lines(proc.stdout):
                safe = _safe_line(raw, self.settings.token)
                with log_path.open("a", encoding="utf-8") as log:
                    log.write(safe + "\n")
                try:
                    event = json.loads(raw)
                except (json.JSONDecodeError, ValueError):
                    continue
                if not isinstance(event, dict) or event.get("name") != table:
                    continue
                if event.get("event") in {"table_started", "table_progress", "table_completed", "table_failed"}:
                    safe_event = dict(event)
                    if "error_message" in safe_event:
                        safe_event["error_message"] = _safe_line(str(safe_event["error_message"]), self.settings.token)[:1000]
                    on_event(safe_event)
                if event.get("event") == "table_failed":
                    saw_explicit_failure = True
                    last_safe_error = _safe_line(str(event.get("error_message", "Sync script reported failure")), self.settings.token)[:1000]
                if event.get("event") == "table_completed" and event.get("published") is True:
                    saw_publication = True
        try:
            await asyncio.wait_for(consume(), timeout=self.settings.sync_timeout_seconds)
            returncode = await asyncio.wait_for(proc.wait(), timeout=10)
        except asyncio.CancelledError:
            await self._stop(proc)
            raise
        except asyncio.TimeoutError:
            await self._stop(proc)
            return AdapterResult(returncode=124, saw_publication=False, uncertain=True)
        except Exception:
            await self._stop(proc)
            raise
        if last_safe_error:
            with log_path.open("a", encoding="utf-8") as log:
                log_path.chmod(0o600)
                log.write(f"safe error: {last_safe_error}\n")
        if saw_explicit_failure:
            return AdapterResult(returncode=returncode or 1, saw_publication=False)
        if returncode == 0 and saw_publication:
            return AdapterResult(returncode=returncode, saw_publication=True)
        return AdapterResult(returncode=returncode or 1, saw_publication=False, uncertain=True)

    @staticmethod
    async def _stop(proc) -> None:
        if proc.returncode is not None:
            return
        try:
            os.killpg(proc.pid, signal.SIGTERM)
        except AttributeError:
            proc.terminate()
        except ProcessLookupError:
            pass
        try:
            await asyncio.wait_for(proc.wait(), timeout=10)
        except asyncio.TimeoutError:
            try:
                os.killpg(proc.pid, signal.SIGKILL)
            except AttributeError:
                proc.kill()
            except ProcessLookupError:
                pass
            await proc.wait()

