# Copyright (C) 2007-2026 Ahmet Öztürk (aoz_2@yahoo.com)
#
# This file is part of Lifeograph.
#
# Lifeograph 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.
#
# Lifeograph 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 Lifeograph.  If not, see <http://www.gnu.org/licenses/>.

from LoG import *
import json
import datetime
import markdown_parsing as mdp

NAME="Claude History Json (Experimental)"
VERSION="0.1"
CATEGORY=SCtg.IMPORTER

_NOW = Date.get_now()

def run(path):
    dm = Diary.get_main()

    with open(path, "r", encoding="utf-8") as f:
        conversations = json.load(f)

    entry_root = dm.create_entry_rel(None, True, "Claude Import")
    entry_root.append_paragraph(f"Imported on {Date.format_str(_NOW, 'F, T')}")

    for conv in conversations:
        title = conv.get("name") or ""
        if not title: #skip empty conversatons
            continue

        messages = conv.get("chat_messages", {})
        date_str = conv.get("created_at") or ""
        uuid = conv.get("uuid", "")

        _import_entry(dm, entry_root, title, _iso_to_datev(date_str), messages, uuid)

    show_message("Import complete!")
    refresh_panels()

    return True

# HELPERS
def _iso_to_datev(iso_date):
    if iso_date:
        try:
            dt = datetime.datetime.fromisoformat(iso_date)
        except (ValueError, TypeError):
            pass
        else:
            return Date.make(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
    return _NOW

def _import_entry(diary, entry_root, title, date_c, messages, uuid):
    entry = diary.create_entry_rel(entry_root, True, title)
    entry.set_creation_date(date_c)
    para = entry.append_paragraph(uuid)
    para.add_format(VT.FMT.FADED)

    for msg in messages:
        author = msg.get("sender", "unknown")

        content_list = msg.get("content", {})
        for content in content_list:
            if content.get("type", "") == "text":
                date_str = content.get("start_timestamp", "")
                date = _iso_to_datev(date_str)

                para = entry.append_paragraph(author)
                para.set_alignment(VT.PA.RIGHT if author == "human" else VT.PA.LEFT)
                para.set_hrule(True)
                para.set_heading_level(VT.PHS.LARGE)

                para = entry.append_paragraph(f"{Date.format_str(date, "F, T")}")
                para.set_alignment(VT.PA.RIGHT if author == "human" else VT.PA.LEFT)

                text = content.get("text", "")
                mdp.import_markdown(entry, text)

                entry.append_paragraph("") # add an empty para for stronger separation


