import sys, socket, ujson # pyright: ignore[reportMissingModuleSource]
from rp2 import * # pyright: ignore[reportMissingModuleSource]

class DNSResolutionError(Exception):...
class ConnectionError(Exception):...
class DisconnectError(Exception):...

class Response:
	def __init__(self, response_code: int, headers: dict[str,str], content: bytes|None):
		self.response_code = response_code
		self.headers = headers
		self.content = content
		try:
			self.text = self.content.decode() if self.content is not None else None
		except:
			self.text = None

	def json(self):
		if self.text is not None:
			return ujson.loads(self.text)
		raise ValueError

class URI:
	def __init__(self, uri: str) -> None:
		self.protocol, uri = uri.split('://') if '://' in uri else (None, uri)
		conn = uri.split('/')[0] if '/' in uri else uri
		conn = conn.split('?')[0] if '?' in conn else conn
		auth, conn = (conn.split('@')[0], '@'.join(conn.split('@')[1:])) if '@' in conn else (None, conn)
		self.user, self.password = auth.split(':') if auth is not None and ':' in auth else (None, None)
		self.hostname, self.port = conn.split(':') if ':' in conn else (conn, None) if conn != '' else (None, None)
		self.path = '/' + '/'.join(uri.split('/')[1:]) if '/' in uri else '?' + uri.split('?')[1] if '?' in uri else None
		self.path, self.querystring = self.path.split('?') if self.path is not None and '?' in self.path else (self.path, None)
		self.path = None if self.path == '' else self.path

	@classmethod
	def construct(cls, protocol=None, user=None, password=None, hostname=None, port=None, path=None, querystring=None):
		obj = cls('')

		obj.protocol = protocol
		obj.user = user
		obj.password = password
		obj.hostname = hostname
		obj.port = port
		obj.path = path
		obj.querystring = querystring

		return obj

	def __str__(self) -> str:
		return (f'{self.protocol}://' if self.protocol is not None else '') + \
			(f'{self.user}:{self.password}@' if self.user is not None and self.password is not None else '') + \
			(self.hostname if self.hostname is not None else '') + \
			(f':{self.port}' if self.port is not None else '') + \
			(self.path if self.path is not None else '') + \
			(f'?{self.querystring}' if self.querystring is not None else '')

	def json(self):
		return {
			'protocol': self.protocol,
			'user': self.user,
			'password': self.password,
			'hostname': self.hostname,
			'port': self.port,
			'path': self.path,
			'querystring': self.querystring
		}

def rel_uri(base: str, relative: str) -> str:
	baseuri = URI(base)
	reluri = URI(relative)
	if reluri.protocol is not None and reluri.hostname is not None:
		return relative
	elif reluri.path is not None:
		return str(URI.construct(protocol=baseuri.protocol, hostname=baseuri.hostname, port=baseuri.port, path=reluri.path, querystring=reluri.querystring))
	elif reluri.querystring is not None:
		return str(URI.construct(protocol=baseuri.protocol, hostname=baseuri.hostname, port=baseuri.port, path=baseuri.path, querystring=reluri.querystring))
	else:
		return base

class Connection:
	def __init__(self, default_callback_msg=None):
		self._s = None
		self._connected_to = None
		self.connected = False
		self.default_callback_msg = default_callback_msg
		self.dns_cache = {}

	def _callback_msg(self, message, reason, prefered_callback=None):
		if prefered_callback is not None:
			prefered_callback(message, reason)
		elif self.default_callback_msg:
			self.default_callback_msg(message, reason)

	def resolve_dns(self, hn, callback_msg=None):
		if hn not in self.dns_cache:
			self._callback_msg('Querying DNS','DNS', callback_msg)
			retry=3
			while True:
				try:
					addrs = socket.getaddrinfo(hn, 80)
					self.dns_cache[hn] = addrs[0][-1][0]
					break
				except:
					retry-=1
					if retry <= 0:
						raise DNSResolutionError
		return self.dns_cache[hn]

	def connect(self, hn, callback_msg=None):
		uri = URI(hn)
		ip = self.resolve_dns(uri.hostname)
		port = int(uri.port) if uri.port is not None else 80
		self._callback_msg('Connecting','connect', callback_msg)
		self._s = socket.socket()
		try:
			self._s.connect((ip, port))
		except OSError:
			raise ConnectionError
		self._connected_to = (ip, port)
		self.connected = True

	def close(self, callback_msg=None):
		if self.connected:
			assert self._s is not None
			self._callback_msg('Closed connection','close', callback_msg)
			self._s.close()
			self._s = None
			self._connected_to = None
			self.connected = False
		else:
			self._callback_msg('Connection already closed', 'close', callback_msg)

	def get(
		self,
		uri,
		file=None,
		headers=None,
		keep_alive=None,
		callback_progress=None,
		callback_msg=None,
		follow_redirects: bool=True,
		retry_on_timeout: int=3
	):
		"""
		HTTP GET request.
		ARGS:
		- uri: The resource to fetch.
		- file: Where to save the data. (If none, return as responce.body)
		- headers: A dictionary of headers to merge with the default headers.
		- keep_alive: If true, the 'Connection' header will be 'keep-alive', and the connection will not be closed.
		- callback_progress: Function to call with progress. callback_progress(total_bytes, xferd_bytes)
		- callback_msg: Function to report the stage of the download. callback_msg(msg, reason)
			-- Querying DNS (reason=DNS)
			-- Connecting (reason=connect)
			-- Making request (reason=request)
			-- Waiting for headers (reason=wait_headers)
			-- Waiting for body (reason=wait_headers)
		"""
		sp_uri = URI(uri)
		self._callback_msg(str(uri), 'GET', prefered_callback=callback_msg)
		protocol = sp_uri.protocol
		hn = sp_uri.hostname
		port = int(sp_uri.port) if sp_uri.port is not None else 80
		resource = sp_uri.path if sp_uri.path is not None else '/'

		if self.connected:
			assert self._connected_to is not None
			if self._connected_to[0] != self.resolve_dns(hn) or self._connected_to[1] != port:
				self._callback_msg('Must connect to alternate server.', 'GET')
				self.close()
				self.connect(uri)
			if keep_alive is None:
				keep_alive = True
		else:
			if keep_alive is None:
				keep_alive = False
			self.connect(uri, callback_msg=callback_msg)
		assert self._s is not None

		#MKREQUEST
		if callback_msg:callback_msg('Sending request','request')
		if headers is None:headers={'Host': hn, 'User-Agent': f'curl/8.20.0'}
		headers['Connection'] = 'keep-alive' if keep_alive else 'close'
		request_ln = f'GET {resource} HTTP/1.1\r\n'
		headers_ln = '\r\n'.join([f'{key}: {val}' for key, val in headers.items()])
		self._s.send(bytes(request_ln+headers_ln+'\r\n\r\n','UTF-8'))

		#RECVHEADERS
		if callback_msg:callback_msg('Waiting for headers','wait_headers')
		headertxt = b''
		while not str(headertxt, 'UTF-8').endswith('\r\n\r\n'):
			headertxt+=self._s.recv(1)
		headertxt = str(headertxt, 'UTF-8')
		resp_status_ln = headertxt.split('\r\n\r\n')[0]
		resp_ver, resp_code = resp_status_ln.split()[0:2]
		resp_code_name = ' '.join(resp_status_ln.split()[2:])
		resp_headers_ln = headertxt.split('\r\n\r\n')[0].split('\r\n')[1:]
		resp_headers = {}
		for header in resp_headers_ln:
			key=header.split(': ')[0].lower()
			val=': '.join(header.split(': ')[1:])
			resp_headers[key]=val

		#RECVBODY
		if callback_msg:callback_msg('Waiting for body','wait_body')
		content_length = int(resp_headers['content-length'])
		body = b''
		body_len = 0
		if file is None:
			while body_len != content_length:
				data = self._s.recv(min(1024,(content_length-body_len)))
				body_len += len(data)
				body += data
		else:
			with open(file, 'wb') as f:
				while body_len != content_length:
					data = self._s.recv(min(1024,(content_length-body_len)))
					body_len += len(data)
					f.write(data)
		if resp_headers.get('connection') == 'close' or headers.get('Connection') == 'close':self.close(callback_msg=callback_msg)
		if follow_redirects and resp_code in ['302', '303']:
			return self.get(
				rel_uri(uri, resp_headers['location']),
				file=file,
				headers=headers,
				keep_alive=keep_alive,
				callback_progress=callback_progress,
				callback_msg=callback_msg,
				follow_redirects=follow_redirects,
				retry_on_timeout=retry_on_timeout
			)
		elif retry_on_timeout > 0 and resp_code in ['408']:
			return self.get(
				uri,
				file=file,
				headers=headers,
				keep_alive=keep_alive,
				callback_progress=callback_progress,
				callback_msg=callback_msg,
				follow_redirects=follow_redirects,
				retry_on_timeout=retry_on_timeout-1
			)
		else:
			return Response(int(resp_code), resp_headers, body)

def get(*args, **kwargs):
	c = Connection()
	return c.get(*args,**kwargs)

__version__ = '0.1.0'
__author__ = 'Rowan Denny'
__email__ = 'iweartwohats@gmail.com'
