# This is free software for the public good of a permacomputer hosted at
# permacomputer.com, an always-on computer by the people, for the people.
# One which is durable, easy to repair, & distributed like tap water
# for machine learning intelligence.
#
# The permacomputer is community-owned infrastructure optimized around
# four values:
#
#   TRUTH      First principles, math & science, open source code freely distributed
#   FREEDOM    Voluntary partnerships, freedom from tyranny & corporate control
#   HARMONY    Minimal waste, self-renewing systems with diverse thriving connections
#   LOVE       Be yourself without hurting others, cooperation through natural law
#
# This software contributes to that vision by archiving the web, preserving digital knowledge before it disappears.
# Code is seeds to sprout on any abandoned technology.

"""Archive/tarball mode for serving from .tar.gz files.
# Side quest 6/21: Everything compressed eventually expands.
"""

import sqlite3
import tarfile
from pathlib import Path
from typing import Dict, Optional, Tuple

# Tarball mode globals
TAR_PATH: str = None
TAR_OFFSET: int = 0  # Offset for .run files
TAR_MEMBERS: Dict[str, tarfile.TarInfo] = {}
TAR_MEDIA_INDEX: Dict[str, str] = {}  # md5_hash -> full path
ARCHIVE_ROOT: str = None
TEMP_DB_PATH: str = None


def _open_tarball():
    """Open a fresh tarball handle for this thread."""
    if TAR_OFFSET > 0:
        f = open(TAR_PATH, 'rb')
        f.seek(TAR_OFFSET)
        return tarfile.open(fileobj=f, mode='r:gz')
    return tarfile.open(TAR_PATH, 'r:gz')


def read_from_tarball(path: str) -> Optional[bytes]:
    """Read a file from the tarball. Thread-safe."""
    if not TAR_PATH or not ARCHIVE_ROOT:
        return None
    full_path = f"{ARCHIVE_ROOT}/{path}"
    if full_path in TAR_MEMBERS:
        member = TAR_MEMBERS[full_path]
        tar = _open_tarball()
        try:
            f = tar.extractfile(member)
            if f:
                return f.read()
        finally:
            tar.close()
    return None


def find_media_in_tarball(md5_hash: str) -> Tuple[Optional[bytes], Optional[str]]:
    """Find media file in tarball by hash. Returns (data, extension)."""
    if not TAR_PATH or not ARCHIVE_ROOT:
        return None, None

    if md5_hash in TAR_MEDIA_INDEX:
        name = TAR_MEDIA_INDEX[md5_hash]
        member = TAR_MEMBERS.get(name)
        if member:
            tar = _open_tarball()
            try:
                f = tar.extractfile(member)
                if f:
                    ext = Path(name).suffix
                    return f.read(), ext
            finally:
                tar.close()
    return None, None


class ArchiveDB:
    """Simple sync SQLite wrapper for archive.db (FTS5 search)."""
    
    def __init__(self, db_path):
        self.conn = sqlite3.connect(db_path)
        self.conn.row_factory = sqlite3.Row

    async def search_pages(self, query, limit=50):
        cursor = self.conn.execute(
            "SELECT uri, title, snippet(pages_fts, 2, '<b>', '</b>', '...', 32) as snippet "
            "FROM pages_fts WHERE pages_fts MATCH ? LIMIT ?",
            (query, limit)
        )
        return [dict(row) for row in cursor.fetchall()]

    async def get_stats(self):
        cursor = self.conn.execute("SELECT COUNT(*) FROM pages")
        return {"pages": cursor.fetchone()[0], "media": 0, "screenshots": 0}
