import json
import pandas as pd
import pytest
import sys

from tidyfit.cli import main
from tidyfit.data import train_val_test_split, validate_schema, distribution_summary
from tidyfit.features import drop_high_correlation
from tidyfit.reproducibility import set_global_seed


def test_data_error_branches():
    df = pd.DataFrame({"x": [1, 2], "y": [0, 1]})
    with pytest.raises(ValueError):
        train_val_test_split(df, target="missing")
    with pytest.raises(ValueError):
        train_val_test_split(df, target="y", train_size=0.9, val_size=0.2)


def test_schema_errors_and_distribution():
    df = pd.DataFrame({"x": [1, 2], "y": [0, 1]})
    ok, errs = validate_schema(df, {"x": "float64", "z": "int64"})
    assert not ok
    assert any(e.startswith("missing:z") for e in errs)
    dist = distribution_summary(df, ["x", "y"])
    assert "x" in dist.index


def test_drop_high_correlation():
    df = pd.DataFrame({"a": [1, 2, 3], "b": [2, 4, 6], "c": [1, 0, 1]})
    out = drop_high_correlation(df, threshold=0.9)
    assert len(out.columns) < len(df.columns)


def test_seed_with_optional_torch_path():
    set_global_seed(7, torch=True)


def test_cli_paths(tmp_path, capsys):
    p = tmp_path / "d.csv"
    pd.DataFrame({"f": [1, 2, 3], "y": [0, 1, 1], "score": [0.1, 0.8, 0.9]}).to_csv(
        p, index=False
    )

    sys.argv = ["tidyfit", "imbalance-report", str(p), "--target", "y"]
    main()
    assert "count" in capsys.readouterr().out

    sys.argv = [
        "tidyfit",
        "threshold-sweep",
        str(p),
        "--label-col",
        "y",
        "--score-col",
        "score",
    ]
    main()
    assert "threshold" in capsys.readouterr().out

    out = tmp_path / "env.json"
    sys.argv = ["tidyfit", "env-snapshot", "--out", str(out)]
    main()
    payload = json.loads(out.read_text())
    assert "python" in payload
