import http.server
import urllib.parse
import webbrowser
import requests
import json

CLIENT_ID = '427337208745-ngsse98cvviaq9vj5245umd6fihjvvoo.apps.googleusercontent.com'
CLIENT_SECRET = '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'
REDIRECT_URI = 'http://localhost:9876'
SCOPE = 'https://www.googleapis.com/auth/blogger'


class OAuthHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)
        params = urllib.parse.parse_qs(parsed.query)

        if 'code' in params:
            auth_code = params['code'][0]
            print("Got auth code: " + auth_code[:20] + "...")

            token_resp = requests.post('https://oauth2.googleapis.com/token', data={
                'client_id': CLIENT_ID,
                'client_secret': CLIENT_SECRET,
                'code': auth_code,
                'grant_type': 'authorization_code',
                'redirect_uri': REDIRECT_URI,
            })
            tokens = token_resp.json()

            if 'access_token' in tokens:
                print("Access Token: " + tokens["access_token"][:30] + "...")
                print("Refresh Token: " + tokens.get("refresh_token", "NONE"))

                with open('tools/admin/blogger_tokens.json', 'w') as f:
                    json.dump(tokens, f, indent=2)
                print("Tokens saved to tools/admin/blogger_tokens.json")

                self.send_response(200)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                self.wfile.write(b'<h1>Success! Blogger authorized.</h1><p>You can close this tab.</p>')
            else:
                print("Token error: " + json.dumps(tokens))
                self.send_response(400)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                self.wfile.write(("Error: " + json.dumps(tokens, indent=2)).encode())

            import threading
            threading.Thread(target=self.server.shutdown).start()
        else:
            self.send_response(400)
            self.end_headers()
            self.wfile.write(b'No code received')

    def log_message(self, format, *args):
        pass


print("Starting OAuth flow...")
print("A browser window will open. Sign in and authorize the app.")
print()

auth_url = (
    "https://accounts.google.com/o/oauth2/v2/auth"
    "?client_id=" + CLIENT_ID
    + "&redirect_uri=" + urllib.parse.quote(REDIRECT_URI)
    + "&response_type=code"
    + "&scope=" + urllib.parse.quote(SCOPE)
    + "&access_type=offline"
    + "&prompt=consent"
)

server = http.server.HTTPServer(('localhost', 9876), OAuthHandler)
webbrowser.open(auth_url)
print("Waiting for authorization...")
server.handle_request()
server.handle_request()
print("Done!")
