"""Slow model test — fits on synthetic data to verify model recovers known relationships.

Run with: pytest tests/test_modeling/test_engine_slow.py -v
"""

import pytest


@pytest.mark.slow
def test_model_recovers_channel_relationships(synthetic_csv_path):
    """Verify model roughly recovers that Google Search has higher ROAS than Email.

    This is a smoke test — we don't expect exact recovery with 30 weeks of data,
    but the relative ordering should hold.
    """
    import pandas as pd

    from mixlift.modeling.engine import run_full_pipeline
    from mixlift.modeling.preprocessing import prepare_model_data

    # Load synthetic data
    raw = pd.read_csv(synthetic_csv_path)

    # Build canonical format from wide synthetic format
    dates = pd.to_datetime(raw["date"])
    channel_spend_cols = [c for c in raw.columns if c.endswith("_spend")]
    channels = [c.replace("_spend", "").replace("_", " ").title() for c in channel_spend_cols]

    rows = []
    for _, row in raw.iterrows():
        for col, channel in zip(channel_spend_cols, channels):
            rows.append({
                "date": row["date"],
                "channel": channel,
                "spend": row[col],
                "impressions": row.get(col.replace("_spend", "_impressions"), 0),
                "clicks": row.get(col.replace("_spend", "_clicks"), 0),
                "conversions": row.get(col.replace("_spend", "_conversions"), 0),
            })

    canonical = pd.DataFrame(rows)
    canonical["date"] = pd.to_datetime(canonical["date"])

    # Prepare target
    target = pd.Series(raw["revenue"].values, index=dates)

    X, y, channel_columns = prepare_model_data(canonical, target)

    # Fit with fast config
    from mixlift.modeling.defaults import FAST_CONFIG

    results = run_full_pipeline(X, y, channel_columns, mcmc_config=FAST_CONFIG)

    # Verify we got results for all channels
    assert len(results.channel_contributions) == len(channel_columns)
    assert len(results.roas_estimates) == len(channel_columns)

    # Most ROAS should be positive; with fast MCMC on 30 weeks,
    # low-signal channels may get slightly negative estimates
    positive_count = sum(1 for v in results.roas_estimates.values() if v > 0)
    assert positive_count >= len(channel_columns) // 2, (
        f"Too many negative ROAS: {results.roas_estimates}"
    )

    # Google Search should have high ROAS (ground truth: 3.2x)
    # We just check it's above 1.0 as a smoke test
    google_roas = results.roas_estimates.get("Google Search", 0)
    assert google_roas > 0.5, f"Google Search ROAS too low: {google_roas}"

    print(f"\nModel results (fitted in {results.duration_secs:.1f}s):")
    for channel, roas in sorted(results.roas_estimates.items(), key=lambda x: -x[1]):
        print(f"  {channel}: ROAS={roas:.2f}x")
