"""Tests for the auto-scan scheduler and email alert logic (no real emails)."""
from datetime import datetime, timezone, timedelta

from app.services.scheduler import is_market_hours, scheduler
from app.services.alerts import alerts_enabled, build_signal_email
from app import models

ET = timezone(timedelta(hours=-5))


def test_market_hours_weekday_open():
    assert is_market_hours(datetime(2026, 7, 13, 10, 30, tzinfo=ET))   # Mon 10:30
    assert is_market_hours(datetime(2026, 7, 13, 9, 30, tzinfo=ET))    # open bell
    assert not is_market_hours(datetime(2026, 7, 13, 9, 29, tzinfo=ET))
    assert not is_market_hours(datetime(2026, 7, 13, 16, 0, tzinfo=ET))  # close


def test_market_hours_weekend_closed():
    assert not is_market_hours(datetime(2026, 7, 12, 11, 0, tzinfo=ET))  # Sunday
    assert not is_market_hours(datetime(2026, 7, 11, 11, 0, tzinfo=ET))  # Saturday


def test_alerts_disabled_without_config(monkeypatch):
    for k in ("EMAIL_ALERTS_ENABLED", "SMTP_USER", "SMTP_PASSWORD", "ALERT_EMAIL_TO"):
        monkeypatch.delenv(k, raising=False)
    assert alerts_enabled() is False
    monkeypatch.setenv("EMAIL_ALERTS_ENABLED", "true")
    assert alerts_enabled() is False  # still missing SMTP credentials


def test_alerts_enabled_with_full_config(monkeypatch):
    monkeypatch.setenv("EMAIL_ALERTS_ENABLED", "true")
    monkeypatch.setenv("SMTP_USER", "a@b.com")
    monkeypatch.setenv("SMTP_PASSWORD", "secret")
    monkeypatch.setenv("ALERT_EMAIL_TO", "a@b.com")
    assert alerts_enabled() is True


def test_signal_email_contents():
    s = models.Signal(
        symbol="TSLA", company="Tesla Inc", direction="CALL", status="approved",
        risk_rating="medium", price=250.0, confidence=82.0, probability=64.0,
        entry=250.0, stop_loss=241.0, target1=268.0, target2=277.0,
        risk_reward=2.0, position_size=111, max_risk_usd=999.0,
    )
    subject, text, html = build_signal_email([s])
    assert "TSLA" in subject and "1 new approved signal" in subject
    for body in (text, html):
        assert "TSLA" in body and "250.00" in body and "241.00" in body
    assert "not financial advice" in text


def test_scheduler_status_shape():
    status = scheduler.status()
    for key in ("enabled", "running", "interval_minutes", "market_hours_now",
                "alerts_configured", "last_run", "runs", "last_result"):
        assert key in status
    assert status["running"] is False  # not started in tests
