import json
from datetime import datetime
from typing import Any

from modules.classes import DatabaseConnectionManager

VALID_PORTALS = {"no", "otodom", "domiporta", "tabelaofert", "gruntguru"}


def _utcnow_iso() -> str:
    return datetime.utcnow().replace(microsecond=0).isoformat()


def _ensure_sync_tables(conn) -> None:
    cursor = conn.cursor()
    cursor.execute(
        """
        CREATE TABLE IF NOT EXISTS offer_portal_sync (
            offer_id INTEGER NOT NULL,
            portal_key TEXT NOT NULL,
            is_published INTEGER NOT NULL DEFAULT 0,
            needs_update INTEGER NOT NULL DEFAULT 0,
            last_action TEXT,
            last_filename TEXT,
            last_bytes INTEGER,
            last_error TEXT,
            last_uploaded_at TEXT,
            updated_at TEXT NOT NULL,
            PRIMARY KEY (offer_id, portal_key)
        )
        """
    )
    cursor.execute(
        """
        CREATE TABLE IF NOT EXISTS offer_portal_sync_events (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            offer_id INTEGER NOT NULL,
            portal_key TEXT,
            event_type TEXT NOT NULL,
            payload_json TEXT,
            created_at TEXT NOT NULL
        )
        """
    )


def _insert_event(conn, *, offer_id: int, portal_key: str | None, event_type: str, payload: dict[str, Any]) -> None:
    cursor = conn.cursor()
    cursor.execute(
        """
        INSERT INTO offer_portal_sync_events (offer_id, portal_key, event_type, payload_json, created_at)
        VALUES (?, ?, ?, ?, ?)
        """,
        (
            int(offer_id),
            portal_key,
            event_type,
            json.dumps(payload, ensure_ascii=False),
            _utcnow_iso(),
        ),
    )


def mark_offer_requires_update(*, offer_id: int, reason: str, changed_fields: list[str] | None = None) -> int:
    now = _utcnow_iso()
    changed_fields = changed_fields or []
    payload = {"reason": reason, "changed_fields": changed_fields}

    with DatabaseConnectionManager() as conn:
        _ensure_sync_tables(conn)
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT portal_key
            FROM offer_portal_sync
            WHERE offer_id = ? AND is_published = 1
            """,
            (int(offer_id),),
        )
        published_rows = cursor.fetchall()
        published_portals = [str(row[0]) for row in published_rows if row and row[0]]

        if not published_portals:
            _insert_event(
                conn,
                offer_id=int(offer_id),
                portal_key=None,
                event_type="update_ignored_no_publication",
                payload=payload,
            )
            conn.commit()
            return 0

        for portal in published_portals:
            cursor.execute(
                """
                UPDATE offer_portal_sync
                SET needs_update = 1,
                    updated_at = ?
                WHERE offer_id = ? AND portal_key = ?
                """,
                (now, int(offer_id), portal),
            )
            _insert_event(
                conn,
                offer_id=int(offer_id),
                portal_key=portal,
                event_type="update_required",
                payload=payload,
            )

        conn.commit()
        return len(published_portals)


def ensure_offer_sync_defaults(*, offer_id: int) -> None:
    now = _utcnow_iso()
    with DatabaseConnectionManager() as conn:
        _ensure_sync_tables(conn)
        cursor = conn.cursor()
        for portal_key in sorted(VALID_PORTALS):
            cursor.execute(
                """
                INSERT INTO offer_portal_sync (
                    offer_id, portal_key, is_published, needs_update, last_action, last_filename,
                    last_bytes, last_error, last_uploaded_at, updated_at
                )
                VALUES (?, ?, 0, 0, 'unpublished', NULL, NULL, NULL, NULL, ?)
                ON CONFLICT(offer_id, portal_key) DO NOTHING
                """,
                (int(offer_id), portal_key, now),
            )
        _insert_event(
            conn,
            offer_id=int(offer_id),
            portal_key=None,
            event_type="sync_defaults_initialized",
            payload={"portals": sorted(VALID_PORTALS)},
        )
        conn.commit()


def set_offer_portal_sync_state(*, offer_id: int, portal_key: str, state: str) -> dict[str, Any]:
    normalized_portal = str(portal_key).strip().lower()
    if normalized_portal not in VALID_PORTALS:
        raise ValueError("Nieprawidlowy portal.")

    normalized_state = str(state).strip().lower()
    allowed_states = {"no_info", "unpublished", "published", "update_required"}
    if normalized_state not in allowed_states:
        raise ValueError("Nieprawidlowy stan.")

    now = _utcnow_iso()
    with DatabaseConnectionManager() as conn:
        _ensure_sync_tables(conn)
        cursor = conn.cursor()

        if normalized_state == "no_info":
            cursor.execute(
                "DELETE FROM offer_portal_sync WHERE offer_id = ? AND portal_key = ?",
                (int(offer_id), normalized_portal),
            )
            _insert_event(
                conn,
                offer_id=int(offer_id),
                portal_key=normalized_portal,
                event_type="sync_state_set",
                payload={"state": normalized_state},
            )
            conn.commit()
            return {
                "portal_key": normalized_portal,
                "state": normalized_state,
                "is_published": 0,
                "needs_update": 0,
                "last_action": "manual_no_info",
            }

        if normalized_state == "unpublished":
            is_published, needs_update = 0, 0
        elif normalized_state == "published":
            is_published, needs_update = 1, 0
        else:
            is_published, needs_update = 1, 1

        last_action = f"manual_{normalized_state}"
        cursor.execute(
            """
            INSERT INTO offer_portal_sync (
                offer_id, portal_key, is_published, needs_update, last_action, last_filename,
                last_bytes, last_error, last_uploaded_at, updated_at
            )
            VALUES (?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, ?)
            ON CONFLICT(offer_id, portal_key) DO UPDATE SET
                is_published = excluded.is_published,
                needs_update = excluded.needs_update,
                last_action = excluded.last_action,
                updated_at = excluded.updated_at
            """,
            (int(offer_id), normalized_portal, is_published, needs_update, last_action, now),
        )
        _insert_event(
            conn,
            offer_id=int(offer_id),
            portal_key=normalized_portal,
            event_type="sync_state_set",
            payload={"state": normalized_state},
        )
        conn.commit()
        return {
            "portal_key": normalized_portal,
            "state": normalized_state,
            "is_published": is_published,
            "needs_update": needs_update,
            "last_action": last_action,
        }

