"""Single source of truth for runtime storage filesystem paths.

Phase 1 resolved every runtime path relative to repo_root(), matching the
old, scattered hardcoded locations exactly. Phase 2 (this file) adds an
external, configurable DATA_DIR on top, in compatibility mode:

    DATA_DIR set         -> external mode: runtime data (databases, offer
                            media, agent avatars, CRM JSON, logs, scraper
                            output) resolves under DATA_DIR.
    DATA_DIR unset/empty -> external mode under the sibling directory
                            <repo parent>/InvestmentData (see data_dir()).
    INVESTMENT_LEGACY_STORAGE=1 (explicit opt-in, used by the test suite)
                         -> legacy mode: identical to Phase 1, everything
                            under repo_root() exactly as before.

Design assets (static/, including static/images/ design assets like logos,
hero images, flags -- see images_dir()) NEVER move to DATA_DIR in either
mode: they are VERSIONED_STATIC, part of the git checkout, not runtime
data. Only RUNTIME_PERSISTENT/RUNTIME_REGENERABLE locations are
DATA_DIR-aware.

Hard constraints (do not violate when editing this file):
  - No DB access.
  - No file/directory writes, no os.makedirs()/mkdir() calls.
  - No import-time side effects of any kind.
  - No Flask import (no `request`, no `current_app`, no `url_for`) --
    this module deals in filesystem paths only, never public URLs. Public
    URL construction (url_for('static', ...) and friends) is a separate
    concern and stays in the modules that already own it.
  - Every path returned is absolute. Legacy paths are anchored to
    repo_root() (derived from this file's own location, never from
    os.getcwd()). External paths are anchored to data_dir() (from the
    DATA_DIR environment variable, read fresh on every call -- never
    cached -- so monkeypatch.setenv("DATA_DIR", ...) takes effect
    immediately, with no module reload required).

Consumers should call these functions at the point of use rather than
caching their return value into a module-level constant at import time:
tests isolate storage by monkeypatching REPO_ROOT / the DATA_DIR env var,
which only works if callers re-resolve the path on every call. Consumers
must never call os.getenv("DATA_DIR") themselves -- this module is the only
place that interprets that variable.
"""
from __future__ import annotations

import os
from pathlib import Path

from modules.core.config import BASE_DIR

# Single source of truth for the repo root, reusing the same
# CWD-independent computation modules/core/config.py already relies on
# (os.path.dirname(__file__)-based), rather than recomputing it a second
# way here.
REPO_ROOT = Path(BASE_DIR)

DATA_DIR_ENV_VAR = "DATA_DIR"
LEGACY_STORAGE_ENV_VAR = "INVESTMENT_LEGACY_STORAGE"
SIBLING_DATA_DIR_NAME = "InvestmentData"


def repo_root() -> Path:
    """Absolute path to the InvestmentWebsite repo root, independent of
    the process's current working directory. This is where the CODE and
    VERSIONED_STATIC assets live, in both legacy and external mode."""
    return REPO_ROOT


def data_dir() -> Path | None:
    """The runtime storage root.

    1. DATA_DIR from the environment, when set and non-empty (explicit override);
    2. otherwise the sibling directory <repo parent>/InvestmentData -- the standard
       layout in development and production, so a bare `python run_local.py` or a
       standalone CLI needs no configuration. It is only computed, never created here.

    There is no automatic fallback into the checkout (instances/). The old
    layout is reachable only by explicitly setting INVESTMENT_LEGACY_STORAGE=1 (the
    test suite does, to keep characterising it); then this returns None.

    Read fresh on every call -- not cached -- so monkeypatch.setenv(...) and
    monkeypatch.setattr(storage_paths, "REPO_ROOT", ...) take effect immediately.
    Independent of the process's current working directory.

    Contract: DATA_DIR, if set, must be an absolute path. A relative value
    is rejected with ValueError rather than silently resolved against the
    process's current working directory -- that would reintroduce exactly
    the CWD-dependence Phase 1 removed.
    """
    raw = os.environ.get(DATA_DIR_ENV_VAR)
    if raw:
        path = Path(raw)
        if not path.is_absolute():
            raise ValueError(
                f"{DATA_DIR_ENV_VAR} must be an absolute path, got relative path: {raw!r}"
            )
        return path
    if os.environ.get(LEGACY_STORAGE_ENV_VAR) == "1":  # strict: no other value (true, yes, " 1 ") counts
        return None
    return REPO_ROOT.parent / SIBLING_DATA_DIR_NAME


def is_external_mode() -> bool:
    return data_dir() is not None


# ---------------------------------------------------------------------------
# databases -- SQLite (legacy: instances/, external: DATA_DIR/databases/)
# ---------------------------------------------------------------------------

def instances_dir() -> Path:
    """Directory holding the application's SQLite databases. Legacy name
    kept for the many existing call sites; in external mode this resolves
    to DATA_DIR/databases/ instead of DATA_DIR/instances/, per the Phase 2
    layout contract."""
    external = data_dir()
    if external is not None:
        return external / "databases"
    return repo_root() / "instances"


def instances_backup_dir() -> Path:
    if is_external_mode():
        return instances_dir() / "backups"
    return instances_dir() / "backup"


def idb_db_path() -> Path:
    return instances_dir() / "IDB.db"


def agents_db_path() -> Path:
    return instances_dir() / "agents.db"


def foreign_offers_db_path() -> Path:
    return instances_dir() / "foreign_offers.db"


def crm_clients_db_path() -> Path:
    return instances_dir() / "crm_clients.db"


# ---------------------------------------------------------------------------
# InvestmentWebsite/static/ -- VERSIONED_STATIC assets. Never DATA_DIR-aware:
# live in the git checkout in both modes.
# ---------------------------------------------------------------------------

def static_dir() -> Path:
    return repo_root() / "InvestmentWebsite" / "static"


def images_dir() -> Path:
    """InvestmentWebsite/static/images/ -- VERSIONED_STATIC assets (logos, hero
    images, flags, portal logos, wojewodztwa/*). Does NOT mean "offer
    photos" any more -- see offer_dir()/offers_root_dir() for that. Always
    resolves inside the repo checkout, in both legacy and external mode."""
    return static_dir() / "images"


def static_data_dir() -> Path:
    """static/data/ -- versioned static data files (e.g.
    polska_wojewodztwa.json). Always in-repo, in both modes."""
    return static_dir() / "data"


# ---------------------------------------------------------------------------
# Offer media (RUNTIME_PERSISTENT): legacy lives inside static/images/<id>/
# (so Flask's built-in static handler already serves it); external mode
# moves it to DATA_DIR/offers/<id>/, a dedicated location distinct from
# static/images/'s design assets.
# ---------------------------------------------------------------------------

def offers_root_dir() -> Path:
    """Parent directory of all per-offer folders."""
    external = data_dir()
    if external is not None:
        return external / "offers"
    # Legacy runtime stays at its original anchor when versioned assets move.
    return repo_root() / "static" / "images"


def offer_dir(offer_id) -> Path:
    """Directory holding one offer's photos, video, description.md,
    notes.md and docs/."""
    return offers_root_dir() / str(offer_id)


# ---------------------------------------------------------------------------
# Agent avatars (RUNTIME_PERSISTENT): legacy mixes them into
# static/images/ alongside offer folders and design assets; external mode
# gives them their own dedicated DATA_DIR/agents/ directory.
# ---------------------------------------------------------------------------

def agents_root_dir() -> Path:
    external = data_dir()
    if external is not None:
        return external / "agents"
    # Legacy avatars are runtime data, not Website design assets.
    return repo_root() / "static" / "images"


def agent_avatar_dir() -> Path:
    """Directory holding agent avatar files (agent_<id>.<ext>)."""
    return agents_root_dir()


# ---------------------------------------------------------------------------
# logs/
# ---------------------------------------------------------------------------

def logs_dir() -> Path:
    external = data_dir()
    if external is not None:
        return external / "logs"
    return repo_root() / "logs"


def website_logs_dir() -> Path:
    return request_logs_dir() / "website"


def request_logs_dir() -> Path:
    """Optional local text-log destination; persistent platform DB stays put."""
    raw = os.environ.get("REQUEST_LOG_DIR")
    if raw:
        path = Path(raw)
        if not path.is_absolute():
            raise ValueError("REQUEST_LOG_DIR must be an absolute path")
        return path
    return logs_dir()


def error_log_path() -> Path:
    return request_logs_dir() / "error.log"


def platform_logs_db_path() -> Path:
    """The one physical platform_logs.db file. Previously defined
    independently in InvestmentWebsite/services/platform_logger.py,
    InvestmentManager/leady_pipeline.py and
    InvestmentManager/routes/leady_logs.py -- now a single source of
    truth. In legacy mode it lives under logs/platform/ (unchanged from
    Phase 1); in external mode it consolidates under DATA_DIR/databases/
    alongside the other SQLite databases, per the Phase 2 layout contract
    (section 11: "wszystkie runtime DB ... w tym ... platform_logs")."""
    if is_external_mode():
        return instances_dir() / "platform_logs.db"
    return logs_dir() / "platform" / "platform_logs.db"


def platform_logs_dir() -> Path:
    """Parent directory of platform_logs_db_path() -- kept for callers that
    need to mkdir it specifically (e.g. InvestmentWebsite/services/platform_logger.py)."""
    return platform_logs_db_path().parent


# ---------------------------------------------------------------------------
# CRM runtime JSON: alerts, knowledge center, schedules. Legacy: under the
# InvestmentManager/ source tree (as they always have been); external:
# DATA_DIR/crm/, fully outside the checkout.
# ---------------------------------------------------------------------------

def investmentmanager_dir() -> Path:
    """The InvestmentManager/ source directory. This is CODE, not runtime
    data -- always in-repo, in both modes."""
    return repo_root() / "InvestmentManager"


def crm_runtime_dir() -> Path:
    external = data_dir()
    if external is not None:
        return external / "crm"
    return investmentmanager_dir()


def alerts_dir() -> Path:
    return crm_runtime_dir() / "alerts"


def knowledge_center_dir() -> Path:
    return crm_runtime_dir() / "knowledge_center"


def knowledge_center_backups_dir() -> Path:
    return knowledge_center_dir() / "backups"


def knowledge_center_notes_path() -> Path:
    return knowledge_center_dir() / "all_notes.json"


def knowledge_center_notifications_path() -> Path:
    return knowledge_center_dir() / "notifications.json"


def knowledge_center_manual_leads_path() -> Path:
    return knowledge_center_dir() / "manual_leads.json"


def schedules_dir() -> Path:
    return knowledge_center_dir() / "schedules"


def schedules_backups_dir() -> Path:
    return schedules_dir() / "backups"


# ---------------------------------------------------------------------------
# Scraper output (RUNTIME_REGENERABLE). Legacy: under
# InvestmentManager/scrapers/data/; external: DATA_DIR/scrapers/, a
# top-level DATA_DIR folder (not nested under crm/, per the Phase 2 layout
# contract).
# ---------------------------------------------------------------------------

def scrapers_dir() -> Path:
    external = data_dir()
    if external is not None:
        return external / "scrapers"
    return investmentmanager_dir() / "scrapers"


def scrapers_data_dir() -> Path:
    """Output directory for the OLX scraper CLI tool
    (InvestmentManager/scrapers/__main__.py), also read back by
    InvestmentManager/routes/lead_hunter_portals.py."""
    return scrapers_dir() / "data"
