from __future__ import annotations

import sqlite3
from pathlib import Path
from datetime import datetime, timezone


class LocalDB:
    def __init__(self, db_path: Path):
        db_path.parent.mkdir(parents=True, exist_ok=True)
        self.db_path = db_path
        self._init()

    def connect(self):
        conn = sqlite3.connect(self.db_path)
        conn.row_factory = sqlite3.Row
        return conn

    def _init(self) -> None:
        with self.connect() as conn:
            conn.execute(
                """
                CREATE TABLE IF NOT EXISTS processed_storage_jobs (
                    job_id TEXT PRIMARY KEY,
                    local_path TEXT NOT NULL,
                    sha256 TEXT NOT NULL,
                    file_size INTEGER NOT NULL,
                    processed_at TEXT NOT NULL
                )
                """
            )
            conn.execute(
                """
                CREATE TABLE IF NOT EXISTS processed_download_requests (
                    request_id TEXT PRIMARY KEY,
                    local_path TEXT NOT NULL,
                    sha256 TEXT NOT NULL,
                    file_size INTEGER NOT NULL,
                    processed_at TEXT NOT NULL
                )
                """
            )
            conn.commit()

    def record_storage_job(self, job_id: str, local_path: str, sha256: str, file_size: int) -> None:
        with self.connect() as conn:
            conn.execute(
                """
                INSERT OR REPLACE INTO processed_storage_jobs
                (job_id, local_path, sha256, file_size, processed_at)
                VALUES (?, ?, ?, ?, ?)
                """,
                (str(job_id), local_path, sha256, int(file_size), datetime.now(timezone.utc).isoformat()),
            )
            conn.commit()

    def record_download_request(self, request_id: str, local_path: str, sha256: str, file_size: int) -> None:
        with self.connect() as conn:
            conn.execute(
                """
                INSERT OR REPLACE INTO processed_download_requests
                (request_id, local_path, sha256, file_size, processed_at)
                VALUES (?, ?, ?, ?, ?)
                """,
                (str(request_id), local_path, sha256, int(file_size), datetime.now(timezone.utc).isoformat()),
            )
            conn.commit()
