import os
import tempfile

# DB paths are bound when the database modules are first imported, so set them first.
_TMP_DIR = tempfile.mkdtemp(prefix="lvar-tests-")
os.environ["DATABASE_PATH"] = os.path.join(_TMP_DIR, "test.db")
os.environ["OCR_DATABASE_PATH"] = os.path.join(_TMP_DIR, "ocr_test.db")
os.environ["OCR_STORAGE_DIR"] = os.path.join(_TMP_DIR, "ocr_storage")
os.environ["ENV"] = ""  # empty, not unset: load_dotenv() never overrides an existing variable
os.environ["MERGE_SOCKET_ENABLED"] = "1"  # the socket is off on the server, but its code is kept and still tested

import pytest
from fastapi.testclient import TestClient

from app.lvar import database
from app.main import app


def _wipe_db():
    for suffix in ("", "-wal", "-shm"):
        try:
            os.remove(database.DATABASE_PATH + suffix)
        except FileNotFoundError:
            pass


@pytest.fixture(autouse=True)
def clean_env(monkeypatch):
    for var in ("API_KEY", "PROJECT_ADMIN_NAME", "PROJECT_ADMIN_PASSWORD",
                "ALLOW_PROJECT_DELETE"):
        # "" rather than delenv: load_dotenv() (re-run on reload of app.main) never
        # overrides an existing variable, so .env values cannot leak into tests.
        monkeypatch.setenv(var, "")
    _wipe_db()
    yield
    _wipe_db()


@pytest.fixture
def client():
    return TestClient(app, raise_server_exceptions=False)


@pytest.fixture
def db(monkeypatch, client):
    """Initialised project database (tables created via the public endpoint)."""
    monkeypatch.setenv("PROJECT_ADMIN_NAME", "admin")
    monkeypatch.setenv("PROJECT_ADMIN_PASSWORD", "s3cret")
    r = client.post("/lvar/project_init/admin/s3cret")
    assert r.json()["message"] == "Project initialized successfully"
    return client


def mde_row(code="AAA", date="2025-01-02", **over):
    row = {
        "date": date, "security_code": code,
        "un_open": 1.0, "un_high": 2.0, "un_low": 0.5, "un_close": 1.5,
        "un_volume": 100, "total_value": 10.0,
        "ad_open": 1.0, "ad_high": 2.0, "ad_low": 0.5, "ad_close": 1.5,
        "ad_volume": 100, "adst_ratio_value": 1.0,
        "pct_change": 0.1, "pct_change_with_dsex": 0.1,
        "create_at": "2025-01-02 00:00:00", "update_at": "2025-01-02 00:00:00",
    }
    row.update(over)
    return row


def msi_row(code="AAA", **over):
    row = {
        "is_active": "Y", "security_code": code, "company_name": "Co",
        "sector": "Bank", "marginable": "Y", "un_close": 1.0, "ad_close": 1.0,
        "volitility": 0.2, "betas": 1.0, "outstanding_shares_mn": 10.0,
        "floating_percent": 50.0, "floating_shares_mn": 5.0,
        "create_at": "2025-01-02 00:00:00", "update_at": "2025-01-02 00:00:00",
    }
    row.update(over)
    return row
