"""PREPROD-5A: canonical DATA_DIR resolution.

    1. DATA_DIR (non-empty) wins;
    2. otherwise the sibling <repo parent>/InvestmentData;
    3. never an automatic fallback into <repo>/instances (legacy only by explicit opt-in).

The suite itself runs with INVESTMENT_LEGACY_STORAGE=1 (tests/conftest.py); these tests
delete it to exercise the production resolution. Everything lives under tmp_path.
"""
import ast
import os
import pathlib
import subprocess
import sys

import pytest

from modules.core import storage_paths

REPO = pathlib.Path(__file__).resolve().parents[2]


@pytest.fixture()
def layout(tmp_path, monkeypatch):
    """<tmp>/Investment (patched REPO_ROOT) next to a not-yet-existing <tmp>/InvestmentData."""
    monkeypatch.delenv(storage_paths.DATA_DIR_ENV_VAR, raising=False)
    monkeypatch.delenv(storage_paths.LEGACY_STORAGE_ENV_VAR, raising=False)
    repo = tmp_path / "Investment"
    repo.mkdir()
    monkeypatch.setattr(storage_paths, "REPO_ROOT", repo)
    return repo, tmp_path / "InvestmentData"


def test_unset_data_dir_resolves_the_sibling(layout):
    repo, sibling = layout
    assert storage_paths.data_dir() == sibling
    assert storage_paths.is_external_mode() is True


def test_empty_data_dir_is_treated_as_unset(layout, monkeypatch):
    _repo, sibling = layout
    monkeypatch.setenv("DATA_DIR", "")
    assert storage_paths.data_dir() == sibling


def test_an_explicit_data_dir_wins_over_the_sibling(layout, monkeypatch, tmp_path):
    explicit = tmp_path / "elsewhere"
    monkeypatch.setenv("DATA_DIR", str(explicit))
    assert storage_paths.data_dir() == explicit
    assert storage_paths.foreign_offers_db_path() == explicit / "databases" / "foreign_offers.db"


def test_a_relative_data_dir_is_still_rejected(layout, monkeypatch):
    monkeypatch.setenv("DATA_DIR", "relative/dir")
    with pytest.raises(ValueError):
        storage_paths.data_dir()


def test_resolution_does_not_depend_on_the_working_directory(layout, monkeypatch, tmp_path):
    _repo, sibling = layout
    other = tmp_path / "somewhere_else"
    other.mkdir()
    monkeypatch.chdir(other)
    assert storage_paths.data_dir() == sibling


def test_the_foreign_db_and_the_other_runtime_paths_are_under_the_sibling(layout):
    _repo, sibling = layout
    assert storage_paths.foreign_offers_db_path() == sibling / "databases" / "foreign_offers.db"
    assert storage_paths.offers_root_dir() == sibling / "offers"
    assert storage_paths.logs_dir() == sibling / "logs"
    assert storage_paths.crm_runtime_dir() == sibling / "crm"


def test_there_is_no_fallback_into_the_checkout_and_nothing_is_created(layout, tmp_path):
    repo, sibling = layout
    for resolver in (storage_paths.instances_dir, storage_paths.idb_db_path, storage_paths.agents_db_path,
                     storage_paths.foreign_offers_db_path, storage_paths.crm_clients_db_path,
                     storage_paths.platform_logs_db_path, storage_paths.offers_root_dir, storage_paths.logs_dir):
        path = resolver()
        assert repo not in path.parents and path != repo
        assert "instances" not in path.parts
    assert not sibling.exists() and not (repo / "instances").exists()   # resolving creates nothing


def test_the_legacy_layout_needs_an_explicit_opt_in(layout, monkeypatch):
    repo, _sibling = layout
    monkeypatch.setenv(storage_paths.LEGACY_STORAGE_ENV_VAR, "1")
    assert storage_paths.data_dir() is None
    assert storage_paths.foreign_offers_db_path() == repo / "instances" / "foreign_offers.db"


@pytest.mark.parametrize("value", ["0", "false", "no", "true", "TRUE", "yes", " 1 ", ""])
def test_only_the_exact_value_1_enables_legacy(layout, monkeypatch, value):
    _repo, sibling = layout
    monkeypatch.setenv(storage_paths.LEGACY_STORAGE_ENV_VAR, value)
    assert storage_paths.data_dir() == sibling


def test_data_dir_beats_the_legacy_flag(layout, monkeypatch, tmp_path):
    explicit = tmp_path / "explicit"
    monkeypatch.setenv("DATA_DIR", str(explicit))
    monkeypatch.setenv(storage_paths.LEGACY_STORAGE_ENV_VAR, "1")

    assert storage_paths.data_dir() == explicit
    assert storage_paths.foreign_offers_db_path() == explicit / "databases" / "foreign_offers.db"


@pytest.mark.skipif(sys.platform != "win32", reason="Windows drive-letter layout")
def test_the_windows_development_layout(layout, monkeypatch):
    monkeypatch.setattr(storage_paths, "REPO_ROOT", pathlib.Path(r"C:\Users\pszymoniak\Desktop\investment\Investment"))
    assert str(storage_paths.data_dir()) == r"C:\Users\pszymoniak\Desktop\investment\InvestmentData"


def test_a_standalone_process_resolves_the_sibling_from_any_directory(tmp_path):
    env = {k: v for k, v in os.environ.items() if k not in ("DATA_DIR", "INVESTMENT_LEGACY_STORAGE")}
    code = ("import sys; sys.path.insert(0, sys.argv[1]);"
            "from modules.core import storage_paths as s; print(s.data_dir()); print(s.foreign_offers_db_path())")
    out = subprocess.run([sys.executable, "-c", code, str(REPO)], cwd=tmp_path, env=env,
                         capture_output=True, text=True, check=True).stdout.split("\n")
    assert pathlib.Path(out[0]) == REPO.parent / "InvestmentData"
    assert pathlib.Path(out[1]) == REPO.parent / "InvestmentData" / "databases" / "foreign_offers.db"


def _names_used(path):
    tree = ast.parse((REPO / path).read_text(encoding="utf-8"))
    return {n.value for n in ast.walk(tree) if isinstance(n, ast.Constant) and isinstance(n.value, str)}


def test_run_local_and_flask_app_use_the_central_resolver_only():
    for entry in ("run_local.py", "flask_app.py"):
        strings = _names_used(entry)
        assert "DATA_DIR" not in strings and "instances" not in strings and "InvestmentData" not in strings, entry
    assert "from flask_app import app" in (REPO / "run_local.py").read_text(encoding="utf-8")


# --- the standalone sync CLIs -------------------------------------------------------


class _EmptyAvarten:
    def fetch_full_catalog(self):
        return []


def test_the_avarten_cli_path_uses_the_sibling_database(layout):
    from InvestmentManager.foreign_sync_sources.avarten_run import run_avarten_foreign_sync

    repo, sibling = layout
    result = run_avarten_foreign_sync(dry_run=True, connector=_EmptyAvarten())

    assert result.run is None
    assert (sibling / "databases" / "foreign_offers.db").is_file()
    assert not (repo / "instances").exists()


def test_the_cyprus_cli_path_uses_the_sibling_database(layout):
    from InvestmentManager.foreign_sync_sources.cyprus_run import run_cyprus_foreign_sync
    from tests.investmentmanager.test_cyprus_sync_adapter import project

    class Client:
        def fetch_projects(self):
            return {"projects": [{"slug": "aloha_homes", "project_url": "https://x.test/pl/Aloha_Homes"}]}

        def fetch_project_details(self, url):
            return project()

    repo, sibling = layout
    result = run_cyprus_foreign_sync(dry_run=True, client=Client())

    assert result.run is None
    assert (sibling / "databases" / "foreign_offers.db").is_file()
    assert not (repo / "instances").exists()
