"""Explicit, read-only local inputs for the isolated IDB-MIG-001 copy.

No dotenv, Streamlit, SSH, automatic InvestmentData discovery or provisioning.
"""
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass, field
from pathlib import Path
from types import MappingProxyType
import sqlite3


@dataclass(frozen=True)
class LocalInputs:
    data_dir: Path
    website_base_url: str = "https://investment-nieruchomosci.com"
    url_responses: dict[str, bytes] = field(default_factory=dict)
    export_settings: dict[str, str] = field(default_factory=dict)

    def __post_init__(self):
        root = Path(self.data_dir)
        if not root.is_absolute() or not root.is_dir():
            raise ValueError("An explicit existing absolute test data directory is required")
        object.__setattr__(self, "data_dir", root.resolve())
        object.__setattr__(self, "url_responses", MappingProxyType(dict(self.url_responses)))
        object.__setattr__(self, "export_settings", MappingProxyType(dict(self.export_settings)))


_inputs = ContextVar("isolated_export_inputs", default=None)
WATERMARK_LOGO_PATH = Path(__file__).resolve().parent / "assets/watermark_logo.png"


def current() -> LocalInputs:
    inputs = _inputs.get()
    if inputs is None:
        raise RuntimeError("Configure explicit LocalInputs before reading export data")
    return inputs


@contextmanager
def use(inputs: LocalInputs):
    token = _inputs.set(inputs)
    try:
        yield
    finally:
        _inputs.reset(token)


def checked_path(path) -> Path:
    resolved = Path(path).resolve()
    if not resolved.is_relative_to(current().data_dir):
        raise ValueError("Export input path is outside the configured data directory")
    return resolved


@contextmanager
def read_connection(path):
    resolved = checked_path(path)
    # mode=ro never provisions a missing database. query_only also rejects writes
    # through the connection when a caller supplies an existing writable file.
    conn = sqlite3.connect(resolved.as_uri() + "?mode=ro", uri=True)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA query_only=ON")
    try:
        yield conn
    finally:
        conn.close()


def idb_db_path():
    return current().data_dir / "databases/IDB.db"


def agents_db_path():
    return current().data_dir / "databases/agents.db"


def foreign_offers_db_path():
    return current().data_dir / "databases/foreign_offers.db"


def foreign_offers_db_candidates():
    return [str(foreign_offers_db_path())]


def local_images_base():
    return current().data_dir / "offers"


def local_offer_dir(offer_id):
    return checked_path(local_images_base() / str(offer_id))


def remote_offer_file(offer_id, filename):
    # Name retained for the copied packager's interface; this is a local path.
    return str(checked_path(local_offer_dir(offer_id) / str(filename)))


def local_agent_photo(agent_id):
    return checked_path(current().data_dir / "agents" / f"agent_{agent_id}.jpg")


def remote_agent_photo(agent_id):
    return str(local_agent_photo(agent_id))
