import os
from typer.testing import CliRunner
from fxhnt.cli import app
from fxhnt.application.fund_config import read_fund_config

runner = CliRunner()

def _isolate(monkeypatch, path):
    if os.path.exists(path): os.remove(path)
    monkeypatch.setattr("fxhnt.cli.get_settings", lambda: _S(f"sqlite:///{path}"))

class _S:
    def __init__(self, dsn): self.operational_dsn = dsn; self.paper_capital = 100_000.0

def test_set_then_show(monkeypatch):
    path = "./.pytest_fund_cli.db"; _isolate(monkeypatch, path)
    r = runner.invoke(app, ["fund-config", "set", "--capital", "250000", "--target-vol", "0.2", "--kelly", "0.5",
                            "--max-venue-weight", "0.6"])
    assert r.exit_code == 0, r.output
    assert "max_venue_weight" in r.output
    assert read_fund_config(f"sqlite:///{path}").capital == 250_000.0
    assert read_fund_config(f"sqlite:///{path}").max_venue_weight == 0.6
    r2 = runner.invoke(app, ["fund-config", "show"])
    assert r2.exit_code == 0
    assert "250000" in r2.output.replace(",", "") or "250000.0" in r2.output.replace(",", "")
    assert "max_venue_weight" in r2.output
    os.remove(path)

def test_set_rejects_bad_value(monkeypatch):
    path = "./.pytest_fund_cli_bad.db"; _isolate(monkeypatch, path)
    r = runner.invoke(app, ["fund-config", "set", "--target-vol", "1.5"])
    assert r.exit_code != 0
    if os.path.exists(path): os.remove(path)

def test_set_no_flags_errors(monkeypatch):
    path = "./.pytest_fund_cli_noflag.db"; _isolate(monkeypatch, path)
    r = runner.invoke(app, ["fund-config", "set"])
    assert r.exit_code != 0
    if os.path.exists(path): os.remove(path)
