import os
import sys
import tempfile

from fastapi.testclient import TestClient


def _client(monkeypatch):
    # Add web-backend root to sys.path so _shared can be imported by main.py
    sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
    from app import db
    monkeypatch.setattr(db, "DB_PATH", os.path.join(tempfile.mkdtemp(), "stock.db"))
    db.init_db()
    from app.main import app
    return TestClient(app)


def test_holdings_intel_endpoint(monkeypatch):
    client = _client(monkeypatch)
    r = client.get("/api/stock/holdings/intel")
    assert r.status_code == 200
    body = r.json()
    assert "holdings" in body and "portfolio_health" in body


def test_holdings_intel_history_endpoint(monkeypatch):
    client = _client(monkeypatch)
    r = client.get("/api/stock/holdings/intel/history?ticker=005930")
    assert r.status_code == 200
    body = r.json()
    assert body["ticker"] == "005930"
    assert "history" in body
    assert isinstance(body["history"], list)


def test_holdings_intel_run_endpoint(monkeypatch):
    client = _client(monkeypatch)
    r = client.post("/api/stock/holdings/intel/run")
    assert r.status_code == 200
    body = r.json()
    assert body["ok"] is True
    assert body["queued"] is True
