#!/usr/bin/env python3
"""Simulasi endpoint BE untuk uji report-application.py & check-quota.py."""
import json
from http.server import BaseHTTPRequestHandler, HTTPServer

TOKEN = "test-token-123"

class H(BaseHTTPRequestHandler):
    def _log_request(self):
        length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(length).decode() if length else ""
        print(f"\n>>> {self.command} {self.path}", flush=True)
        print(f"    X-Internal-Token: {self.headers.get('X-Internal-Token')}", flush=True)
        print(f"    body: {body}", flush=True)
        return body

    def do_POST(self):
        body = self._log_request()
        if self.headers.get("X-Internal-Token") != TOKEN:
            self.send_response(401)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({"error": {"code": "unauthorized", "message": "Token salah"}}).encode())
            return
        if self.path == "/v1/agent/applications":
            data = json.loads(body or "{}")
            resp = {
                "accepted": True,
                "quota": {"used_today": 1, "limit_per_day": 10, "remaining_today": 9,
                          "window_days": 30, "total_used": 1, "total_limit": 300},
                "recorded": {"user_id": data.get("user_id"), "portal": data.get("portal"),
                             "job_title": data.get("job_title")},
            }
            self.send_response(201)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps(resp).encode())
        elif self.path == "/v1/agent/portal-status":
            data = json.loads(body or "{}")
            status = data.get("status")
            if status not in ("connected", "disconnected", "connecting", "expired"):
                self.send_response(422)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"error": {"code": "invalid_status", "message": f"status '{status}' tidak valid"}}).encode())
                return
            self.send_response(201)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({"accepted": True, "portal": data.get("portal"), "status": status}).encode())
        else:
            self.send_response(404)
            self.end_headers()

    def do_GET(self):
        self._log_request()
        if self.path.startswith("/v1/agent/quota"):
            resp = {"used_today": 0, "limit_per_day": 10, "remaining_today": 10,
                    "window_days": 30, "total_used": 0, "total_limit": 300}
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps(resp).encode())
        elif self.path.startswith("/v1/agent/portals"):
            resp = {"portals": [
                {"slug": "jobstreet", "name": "JobStreet", "url": "https://id.jobstreet.com/",
                 "marker_type": "name_contains_value", "marker_name": "is.authenticated", "marker_value": "true", "enabled": True},
                {"slug": "linkedin", "name": "LinkedIn", "url": "https://www.linkedin.com/",
                 "marker_type": "name", "marker_name": "li_at", "enabled": True},
                {"slug": "indeed", "name": "Indeed", "url": "https://id.indeed.com/",
                 "marker_type": "name", "marker_name": "USER", "enabled": True},
                {"slug": "glints", "name": "Glints", "url": "https://glints.com/id/",
                 "marker_type": "name", "marker_name": "", "enabled": True},
                {"slug": "kalibrr", "name": "Kalibrr", "url": "https://www.kalibrr.com/id_ID/",
                 "marker_type": "name", "marker_name": "", "enabled": True},
                {"slug": "techinasia", "name": "Tech in Asia", "url": "https://www.techinasia.com/jobs",
                 "marker_type": "name", "marker_name": "", "enabled": False},
            ]}
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps(resp).encode())
        elif self.path.startswith("/v1/agent/user-profile"):
            resp = {
                "profile": {
                    "level": "staff",
                    "city": "Jakarta",
                    "keywords": ["software engineer"],
                    "salary_min": None,
                    "work_type": None,
                    "exclude_companies": [],
                },
                "priority_jobs": [
                    {"job_url": "https://id.jobstreet.com/id/jobs/999", "title": "Backend Engineer", "source": "chat"},
                ],
            }
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps(resp).encode())
        elif self.path == "/v1/agent/daily-report":
            self.send_response(201)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({"accepted": True}).encode())
        elif self.path.startswith("/v1/agent/portal-status"):
            resp = [
                {"portal": "jobstreet", "status": "connected",
                 "display_name": "ena***@yahoo.com", "verified_at": "2026-08-13T07:35:07+00:00"},
            ]
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps(resp).encode())
        else:
            self.send_response(404)
            self.end_headers()

    def log_message(self, *a):
        pass

if __name__ == "__main__":
    print("test BE listener di http://localhost:9999", flush=True)
    HTTPServer(("127.0.0.1", 9999), H).serve_forever()
