from fontTools.ttLib import TTFont
from flask import Flask, request, jsonify

def to_mac_timestamp(date_text):
	from datetime import datetime, timezone
	MAC_EPOCH = datetime(1904, 1, 1, tzinfo=timezone.utc)
	date = datetime.fromisoformat(date_text.replace('Z', '+00:00'))
	if date.tzinfo is None:
		date = date.replace(tzinfo=timezone.utc)
	return int((date.astimezone(timezone.utc) - MAC_EPOCH).total_seconds())

timestamp = to_mac_timestamp('2000-01-01T00:00:00Z')

app = Flask(__name__)

@app.get('/monitor')
def monitor():
	return 'foldersweb_reset_woff_timestamps_server.py'

@app.post('/reset')
def reset():
	data = request.get_json()

	input_path = data['input']
	output_path = data['output']
	if (not input_path or not output_path):
		return jsonify(error='Internal server error'), 500

	# Explicitly disable automatic timestamp recalculation
	font = TTFont(input_path, recalcTimestamp=False)
	font.recalcTimestamp = False # Keep timestamp recalculation disabled during save

	head = font['head']
	head.created = timestamp
	head.modified = timestamp
	head.checkSumAdjustment = 0 # FontTools re-calculates this during save

	if input_path.lower().endswith('.woff2'):
		font.flavor = 'woff2'
	else:
		font.flavor = 'woff'

	font.save(output_path)

	return ''

if __name__ == '__main__':
	import argparse
	parser = argparse.ArgumentParser()
	parser.add_argument('-p', '--port', type=int, default=53254)
	args = parser.parse_args()

	def port_is_available(host, port):
		import socket
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

		try:
			sock.bind((host, port))
			return True
		except OSError:
			return False
		finally:
			sock.close()

	if not port_is_available('127.0.0.1', args.port):
		print(f'Another server is already using 127.0.0.1:{args.port}')
		import sys
		sys.exit(1)

	app.run(host='127.0.0.1', port=args.port)
