"""
Tests for Feature 13: Web Dashboard.
  - Page routes return HTTP 200
  - API routes return correct JSON schema
  - Audit export produces valid JSON / CSV
Uses a real (temp) Orchestrator with a mocked LLM — no real API calls.
"""

import json
import pytest


# ── Page routes ───────────────────────────────────────────────────────────────

class TestPageRoutes:
    """HTML page routes return 200 OK."""

    async def test_home_returns_200(self, dashboard_client):
        response = await dashboard_client.get("/")
        assert response.status_code == 200

    async def test_memory_page_returns_200(self, dashboard_client):
        response = await dashboard_client.get("/memory")
        assert response.status_code == 200

    async def test_audit_page_returns_200(self, dashboard_client):
        response = await dashboard_client.get("/audit")
        assert response.status_code == 200

    async def test_settings_page_returns_200(self, dashboard_client):
        response = await dashboard_client.get("/settings")
        assert response.status_code == 200


# ── API routes ────────────────────────────────────────────────────────────────

class TestApiRoutes:
    """REST API endpoints return correct schema."""

    async def test_api_chat_returns_reply_key(self, dashboard_client):
        """POST /api/chat with a message returns JSON with a 'reply' key."""
        response = await dashboard_client.post(
            "/api/chat",
            json={"message": "hello"},
        )
        assert response.status_code == 200
        data = response.json()
        assert "reply" in data
        assert isinstance(data["reply"], str)

    async def test_api_chat_empty_message_returns_400(self, dashboard_client):
        """POST /api/chat with an empty message returns 400."""
        response = await dashboard_client.post(
            "/api/chat",
            json={"message": ""},
        )
        assert response.status_code == 400

    async def test_api_audit_returns_logs_and_total(self, dashboard_client):
        """GET /api/audit returns JSON with 'logs' list and 'total' count."""
        response = await dashboard_client.get("/api/audit")
        assert response.status_code == 200
        data = response.json()
        assert "logs" in data
        assert "total" in data
        assert isinstance(data["logs"], list)
        assert isinstance(data["total"], int)

    async def test_api_audit_with_query_filter(self, dashboard_client):
        """GET /api/audit?q=test returns filtered results."""
        response = await dashboard_client.get("/api/audit?q=test")
        assert response.status_code == 200
        data = response.json()
        assert "logs" in data
        assert "total" in data

    async def test_api_audit_export_json_is_valid_json(self, dashboard_client):
        """GET /api/audit/export?fmt=json returns valid JSON."""
        response = await dashboard_client.get("/api/audit/export?fmt=json")
        assert response.status_code == 200
        # Response should be parseable JSON
        parsed = json.loads(response.content)
        assert isinstance(parsed, list)

    async def test_api_audit_export_csv_has_header(self, dashboard_client):
        """GET /api/audit/export?fmt=csv returns CSV with a header row."""
        response = await dashboard_client.get("/api/audit/export?fmt=csv")
        assert response.status_code == 200
        text = response.text
        assert len(text.strip()) > 0
        # Header row should contain column names
        first_line = text.strip().splitlines()[0].lower()
        assert "id" in first_line or "timestamp" in first_line or "action" in first_line

    async def test_api_stats_returns_dict(self, dashboard_client):
        """GET /api/stats returns a stats dict."""
        response = await dashboard_client.get("/api/stats")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, dict)

    async def test_api_skills_returns_skills_list(self, dashboard_client):
        """GET /api/skills returns a list of registered skills."""
        response = await dashboard_client.get("/api/skills")
        assert response.status_code == 200
        data = response.json()
        assert "skills" in data
        assert isinstance(data["skills"], list)
