#!/usr/bin/env python3

"""publisher: Handles atom+index logic.

This file is part of publisher.

SPDX-License-Identifier: GPL-3.0-or-later

Copyright (C) 2026 Muhittin Topalak

publisher is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

import xml.etree.ElementTree as ET
import sys
import pathlib
from datetime import datetime, timezone, timedelta
from uuid import uuid4

print("Select an action:")
print("\t[1] insert new entry")
print("\t[2] update existing entry")
option = input("Action: ")
print()

if option not in ('1', '2'):
    print("Assuming this means \"Exit now.\"")
    sys.exit(0)

ET.register_namespace('', "http://www.w3.org/2005/Atom")
tag = lambda x: '{http://www.w3.org/2005/Atom}' + x

# assuming nobody else messes around with the file while this script is running
tree = ET.parse('../feed.xml')

root = tree.getroot()

entries = root.findall(tag('entry'))

if option == '2':
    print("Which entry do you want to update?")
    for i,e in enumerate(entries):
        e_id = e.find(tag('id')).text
        e_title = e.find(tag('title')).text
        print(f"\t[{i+1}] {e_title} -- {e_id}")

    num = input("Number: ")
    print()

    num = int(num) - 1

    if not (0 <= num <= i):
        sys.exit(1)

    e = entries[num]
    print(f"Selected entry {e.find(tag('title')).text}.")

print()

blog_html_paths = tuple(pathlib.Path.cwd().glob("*.html"))

print("Which HTML file should the entry be based on?")
for i,p in enumerate(blog_html_paths):
    print(f"\t[{i+1}] {p.name}")


num = input("Number: ")
print()

num = int(num) - 1

if not (0 <= num <= i):
    sys.exit(1)

p = blog_html_paths[num]
source = p.read_text(encoding="utf-8")

# awesome html parsing
title = source.split("<title>")[1].split("</title>")[0]
main = source.split("<main>")[1].split("</main>")[0]

print(f"Selected {p.name} -- {title}")
print(f"<main> text length is {len(main)}.")

now = datetime.now(timezone(timedelta(hours=+3))).isoformat(timespec='seconds')
real_now = now

if option == "2":
    updated = e.find(tag('updated')).text
    print("entry <updated> time selection:")
    print(f"\t[1] update to now ({now})")
    print(f"\t[2] keep it as is ({updated})")
    selection = input("Choice: ")
    print()

    if selection == '2':
        now = updated

print(f"<updated> is {now}")

if real_now == now:
    root.find(tag('updated')).text = now
    print("Updated feed's <updated> to the same")
else:
    print("Not changing feed's <updated> also")


# main update
if option == "2":
    e.find(tag('title')).text = title
    e.find(tag('link')).set("href", f"/blog/{p.name}")
    e.find(tag('updated')).text = now
    e.find(tag('content')).text = main
else:
    e_uuid = f"urn:uuid:{uuid4()}" # completely random
    print(f"Set id {e_uuid}")

    e = ET.Element(tag('entry'))
    
    tmp = ET.SubElement(e, tag('id'))
    tmp.text = e_uuid

    tmp = ET.SubElement(e, tag('title'))
    tmp.text = title

    tmp = ET.SubElement(e, tag('link'))
    tmp.set("href", f"/blog/{p.name}")

    tmp = ET.SubElement(e, tag('updated'))
    tmp.text = now

    tmp = ET.SubElement(e, tag('published'))
    tmp.text = now

    tmp = ET.SubElement(e, tag('content'))
    tmp.set("type", "html")
    tmp.text = main

    root.insert(6, e)

dump = ET.tostring(root, encoding="utf-8", xml_declaration=True)

with open("../feed.xml", "wb") as f:
    f.write(dump)
    f.write(b'\n')

print("Feed updated.")

if option == "1":
    print("index.html:")
    print("\t[1] insert to latest")
    print("\t[2] keep it as is")
    selection = int(input("Choice: "))

    if selection not in (1,2):
        sys.exit(1)

    if selection == 1:
        with open("index.html", "r") as f:
            data = f.read()
        MARKER = "<!--marker-->"
        data = data.replace(MARKER, f"{MARKER}\n    <li><a href=\"{p.name}\">{title}</a></li>")
        with open("index.html", "w") as f:
            f.write(data)
        print("Inserted blog post to index.html")
else:
    print("Update your index.html, if <title> or location has been changed.")
