from __future__ import annotations

import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from src.quant_engine.qualitative_sell_strategy_store_v1 import (
    QualitativeSellStoreSpec,
    fetch_recent_sell_strategy_results,
    insert_satellite_recommendation,
    insert_sell_strategy_result,
    resolve_store_path,
)


def test_insert_and_fetch_sell_strategy_result(tmp_path):
    db_path = tmp_path / "test.db"
    result = {
        "code": "005930",
        "generated_at": "2026-06-21T12:00:00+09:00",
        "decision": {
            "action": "TRIM_REVIEW_PARTIAL",
            "conviction": "MEDIUM",
            "market_regime": "TECHNICAL_MARKET",
            "composite_score": 0.42,
            "rationale": "test rationale",
        },
    }
    insert_sell_strategy_result(db_path, result)
    rows = fetch_recent_sell_strategy_results(db_path, "005930")
    assert len(rows) == 1
    assert rows[0]["action"] == "TRIM_REVIEW_PARTIAL"
    assert rows[0]["composite_score"] == 0.42


def test_fetch_returns_empty_list_when_db_missing(tmp_path):
    rows = fetch_recent_sell_strategy_results(tmp_path / "nonexistent.db", "005930")
    assert rows == []


def test_multiple_inserts_ordered_by_generated_at_desc(tmp_path):
    db_path = tmp_path / "test.db"
    for ts in ("2026-06-19T12:00:00", "2026-06-21T12:00:00", "2026-06-20T12:00:00"):
        insert_sell_strategy_result(db_path, {
            "code": "005930", "generated_at": ts,
            "decision": {"action": "HOLD_NO_CONFLUENCE"},
        })
    rows = fetch_recent_sell_strategy_results(db_path, "005930")
    assert [r["generated_at"] for r in rows] == ["2026-06-21T12:00:00", "2026-06-20T12:00:00", "2026-06-19T12:00:00"]


def test_insert_satellite_recommendation(tmp_path):
    db_path = tmp_path / "test.db"
    insert_satellite_recommendation(db_path, "2026-06-21T12:00:00+09:00", {
        "ticker": "042700",
        "score": {"satellite_action": "BUY_CANDIDATE", "attractiveness_score": 0.6, "market_regime": "PERFORMANCE_MARKET"},
    })
    import sqlite3
    conn = sqlite3.connect(db_path)
    row = conn.execute("SELECT ticker, satellite_action, attractiveness_score FROM satellite_recommendations").fetchone()
    conn.close()
    assert row == ("042700", "BUY_CANDIDATE", 0.6)


def test_resolve_store_path_supports_sqlite(tmp_path):
    db_path = resolve_store_path(QualitativeSellStoreSpec(location=tmp_path / "qualitative.db"), ROOT)
    assert str(db_path).endswith("qualitative.db")
