"""GUARDiA ITSM 통합 테스트"""
import httpx, pytest

BASE  = "http://127.0.0.1:9001"
VERIFY = False

@pytest.fixture(scope="session")
def token():
    r = httpx.post(f"{BASE}/api/auth/login",
        json={"username":"admin","password":"1111"}, verify=VERIFY, timeout=10)
    assert r.status_code == 200
    return r.json()["access_token"]

@pytest.fixture
def auth(token):
    return {"Authorization": f"Bearer {token}"}


class TestAuth:
    def test_login_success(self, token):
        assert token and len(token) > 20

    def test_login_wrong_password(self):
        r = httpx.post(f"{BASE}/api/auth/login",
            json={"username":"admin","password":"wrong"}, verify=VERIFY, timeout=10)
        assert r.status_code in (401, 422)

    def test_unauthorized_without_token(self):
        r = httpx.get(f"{BASE}/api/tasks", verify=VERIFY, timeout=10)
        assert r.status_code == 401


class TestTasksAPI:
    def test_list_tasks(self, auth):
        r = httpx.get(f"{BASE}/api/tasks", headers=auth, verify=VERIFY, timeout=10)
        assert r.status_code == 200

    def test_create_sr(self, auth):
        payload = {"title":"[통합테스트] 자동 생성 SR",
                   "sr_type":"INQUIRY", "priority":"LOW", "requested_by":"pytest"}
        r = httpx.post(f"{BASE}/api/tasks", json=payload,
                       headers=auth, verify=VERIFY, timeout=10)
        assert r.status_code in (200, 201)
        data = r.json()
        assert data["title"] == payload["title"]
        assert "sr_id" in data

    def test_dashboard_stats(self, auth):
        # 대시보드는 /api/dashboard/stats 또는 /api/dashboard
        for path in ["/api/dashboard/stats", "/api/dashboard"]:
            r = httpx.get(f"{BASE}{path}", headers=auth, verify=VERIFY, timeout=10)
            if r.status_code == 200:
                return
        pytest.skip("대시보드 엔드포인트 경로 확인 필요")


class TestRPAAPI:
    def test_rpa_status(self, auth):
        r = httpx.get(f"{BASE}/api/rpa/status", headers=auth, verify=VERIFY, timeout=10)
        assert r.status_code == 200
        data = r.json()
        assert "validation_rules" in data

    def test_rpa_validations(self, auth):
        r = httpx.get(f"{BASE}/api/rpa/validations", headers=auth, verify=VERIFY, timeout=10)
        assert r.status_code == 200

    def test_rpa_tasks_list(self, auth):
        r = httpx.get(f"{BASE}/api/rpa/tasks", headers=auth, verify=VERIFY, timeout=10)
        assert r.status_code == 200
        assert isinstance(r.json(), list)

    def test_rpa_dry_run_valid(self, auth):
        payload = {"task_type":"SR_CREATE",
                   "payload":{"sr_type":"INQUIRY","title":"[RPA 테스트]",
                               "priority":"LOW","requested_by":"pytest"},
                   "dry_run":True}
        r = httpx.post(f"{BASE}/api/rpa/execute", json=payload,
                       headers=auth, verify=VERIFY, timeout=10)
        assert r.status_code == 200
        assert r.json()["dry_run"] is True

    def test_rpa_dry_run_invalid_enum(self, auth):
        payload = {"task_type":"SR_CREATE",
                   "payload":{"sr_type":"INVALID_TYPE"}, "dry_run":True}
        r = httpx.post(f"{BASE}/api/rpa/execute", json=payload,
                       headers=auth, verify=VERIFY, timeout=10)
        assert r.status_code == 200
        assert r.json()["status"] in ("VALIDATION_FAILED","DRY_RUN_OK")


class TestScrapingAPI:
    def test_scraping_stats(self, auth):
        r = httpx.get(f"{BASE}/api/scraping/stats", headers=auth, verify=VERIFY, timeout=10)
        assert r.status_code == 200
        assert "draft" in r.json()

    def test_scraping_results_list(self, auth):
        r = httpx.get(f"{BASE}/api/scraping/results", headers=auth, verify=VERIFY, timeout=10)
        assert r.status_code == 200
        assert isinstance(r.json(), list)

    def test_scraping_targets_list(self, auth):
        r = httpx.get(f"{BASE}/api/scraping/targets", headers=auth, verify=VERIFY, timeout=10)
        assert r.status_code == 200
        assert isinstance(r.json(), list)


class TestHomepageAPI:
    def test_company_history(self):
        r = httpx.get("http://127.0.0.1:8082/api/history", verify=VERIFY, timeout=10)
        assert r.status_code == 200
        data = r.json()
        assert isinstance(data, list)
        if data:
            assert "year" in data[0]
            assert "items" in data[0]
