"""
Servidor local do Dashboard Financeiro Feegow
"""

import http.server
import urllib.request
import urllib.parse
import json
import os

PORT = 8080
TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmZWVnb3ciLCJhdWQiOiJwdWJsaWNhcGkiLCJpYXQiOjE3ODE2MzU1MTQsImxpY2Vuc2VJRCI6MTAwMzYzMn0.Edk596kKOhi2I-wFuaZblG5j_nsiBUkxhiDH8GCnHGY"
FEEGOW_BASE = "https://api.feegow.com/v1/api"

class Handler(http.server.SimpleHTTPRequestHandler):

    def log_message(self, format, *args):
        first = str(args[0]) if args else ''
        if "/proxy/" in first:
            second = str(args[1]) if len(args) > 1 else ''
            print("  [API] " + first + " -> " + second)

    def do_GET(self):
        if self.path.startswith("/proxy/"):
            self.handle_proxy()
        else:
            super().do_GET()

    def handle_proxy(self):
        path = self.path[len("/proxy"):]
        feegow_url = FEEGOW_BASE + path

        try:
            req = urllib.request.Request(
                feegow_url,
                headers={
                    "x-access-token": TOKEN,
                    "Accept": "application/json",
                    "User-Agent": "FeegowDashboard/1.0"
                }
            )
            with urllib.request.urlopen(req, timeout=15) as resp:
                data = resp.read()
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.send_header("Access-Control-Allow-Origin", "*")
                self.end_headers()
                self.wfile.write(data)

        except urllib.error.HTTPError as e:
            body = e.read()
            self.send_response(e.code)
            self.send_header("Content-Type", "application/json")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()
            self.wfile.write(body)

        except Exception as e:
            error = json.dumps({"success": False, "message": str(e)}).encode()
            self.send_response(500)
            self.send_header("Content-Type", "application/json")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()
            self.wfile.write(error)

    def do_OPTIONS(self):
        self.send_response(204)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.end_headers()


if __name__ == "__main__":
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    print("Dashboard Financeiro - Feegow rodando na porta " + str(PORT))
    with http.server.ThreadingHTTPServer(("0.0.0.0", PORT), Handler) as httpd:
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("Servidor encerrado.")
