from pathlib import Path


def test_production_resource_check_writes_duty_report():
    script = Path("scripts/production_resource_check.sh").read_text(encoding="utf-8")

    assert 'REPORT_PATH="${REPORT_PATH:-/var/lib/xiaoxia-ci/duty_report.json}"' in script
    assert 'API_HEALTH_URL="${API_HEALTH_URL:-http://127.0.0.1:8001/health}"' in script
    assert 'WEB_HEALTH_URL="${WEB_HEALTH_URL:-http://127.0.0.1:3002/}"' in script
    assert "EXPECTED_VERSION" in script
    assert "json.dump(report" in script
    assert "os.replace(tmp_path, report_path)" in script


def test_production_resource_check_has_resource_thresholds():
    script = Path("scripts/production_resource_check.sh").read_text(encoding="utf-8")

    assert 'LOAD_WARN_PER_CPU="${LOAD_WARN_PER_CPU:-1.5}"' in script
    assert 'MEM_AVAILABLE_WARN_MB="${MEM_AVAILABLE_WARN_MB:-256}"' in script
    assert 'DISK_WARN_PERCENT="${DISK_WARN_PERCENT:-85}"' in script
    assert 'SWAP_USED_WARN_PERCENT="${SWAP_USED_WARN_PERCENT:-60}"' in script
    assert "未启用 swap" in script
    assert "根分区磁盘使用率偏高" in script


def test_production_resource_check_tracks_core_containers():
    script = Path("scripts/production_resource_check.sh").read_text(encoding="utf-8")

    for container in [
        "xiaoxia-api-production",
        "xiaoxia-worker-production",
        "xiaoxia-web-production",
        "xiaoxia-postgres-production",
        "xiaoxia-redis-production",
    ]:
        assert container in script


def test_resource_monitoring_runbook_matches_heartbeat_contract():
    docs = Path("docs/PRODUCTION-RESOURCE-MONITORING.md").read_text(encoding="utf-8")

    assert "/var/lib/xiaoxia-ci/duty_report.json" in docs
    assert "ssh xiaoxia-server" in docs
    assert "EXPECTED_VERSION=v0.1.15" in docs
    assert "*/5 * * * *" in docs
    assert "需要老大确认后再启用" in docs
