#!/usr/bin/env python3
import json
import os
import sqlite3
import sys
from typing import Any, Dict, Optional, Tuple

DB_DIR = "/data/error-reports"
DB_PATH = os.path.join(DB_DIR, "error_db.sqlite3")


def ensure_schema(cur: sqlite3.Cursor) -> None:
    cur.execute(
        """
        CREATE TABLE IF NOT EXISTS tbl_claim (
            claim_Id INTEGER PRIMARY KEY AUTOINCREMENT,
            station_id INTEGER NOT NULL,
            claim_description TEXT NOT NULL,
            user_email TEXT,
            state INTEGER NOT NULL DEFAULT 0,
            observation TEXT
        )
        """
    )

    cur.execute("PRAGMA table_info(tbl_claim)")
    columns = {row[1] for row in cur.fetchall()}

    if "state" not in columns:
        cur.execute("ALTER TABLE tbl_claim ADD COLUMN state INTEGER NOT NULL DEFAULT 0")

    if "observation" not in columns:
        cur.execute("ALTER TABLE tbl_claim ADD COLUMN observation TEXT")


def update_claim_state(claim_id: int, state: Optional[int], observation: Optional[str]) -> Optional[Tuple[str, int]]:
    os.makedirs(DB_DIR, mode=0o750, exist_ok=True)
    conn = sqlite3.connect(DB_PATH, timeout=5)
    try:
        cur = conn.cursor()
        ensure_schema(cur)

        cur.execute("SELECT claim_Id, user_email, state FROM tbl_claim WHERE claim_Id = ?", (claim_id,))
        row = cur.fetchone()
        if row is None:
            conn.commit()
            return None

        current_state = int(row[2])
        target_state = state if state is not None else (1 if current_state == 0 else 0)

        cur.execute(
            "UPDATE tbl_claim SET state = ?, observation = ? WHERE claim_Id = ?",
            (target_state, observation, claim_id),
        )
        conn.commit()
        user_email = row[1]
        safe_email = str(user_email).strip() if user_email is not None else ""
        return safe_email, target_state
    finally:
        conn.close()


def main() -> int:
    try:
        payload: Dict[str, Any] = json.load(sys.stdin)
        claim_id = int(payload["claim_id"])
        state_raw = payload.get("state")
        state = None
        if state_raw is not None:
            state = int(state_raw)
        if claim_id <= 0:
            raise ValueError("claim_id must be positive")
        if state is not None and state not in (0, 1):
            raise ValueError("state must be 0 or 1")

        observation = payload.get("observation")
        if observation is not None:
            observation = str(observation)

        update_result = update_claim_state(claim_id, state, observation)
        if update_result is None:
            sys.stdout.write(json.dumps({"ok": False, "error": "Claim not found."}))
            return 2

        _, final_state = update_result

        sys.stdout.write(
            json.dumps({
                "ok": True,
                "claim_id": claim_id,
                "state": final_state,
            })
        )
        return 0
    except Exception as exc:
        sys.stdout.write(json.dumps({"ok": False, "error": str(exc)}))
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
