import clawd_notion as notion
import sys
import json
import os
import subprocess
from datetime import datetime

SESSION_FILE = ".dev_session/SESSION_INFO"

def main():
    if not os.path.exists(SESSION_FILE):
        print("Keine aktive Session.")
        return

    # Parse args manually strictly for summary
    # Usage: python finish_task.py "My Summary"
    summary = sys.argv[1] if len(sys.argv) > 1 else "Update"
    
    with open(SESSION_FILE) as f:
        session = json.load(f)
    
    task_id = session["task_id"]
    
    # 1. Calculate Time & Update "Total Duration (h)"
    start_utc = datetime.fromisoformat(session["start_time"])
    now_utc = datetime.now()
    hours_invested = (now_utc - start_utc).total_seconds() / 3600
    
    # Get current duration from Notion to add to it
    current_duration = notion.get_property_value(task_id, "Total Duration (h)") or 0.0
    new_total = current_duration + hours_invested
    
    # Update the number property
    notion.update_page(task_id, {
        "Total Duration (h)": {"number": round(new_total, 2)}
    })
    
    # 2. Append Status Report Block
    # Convert UTC to Berlin Time (UTC+1/UTC+2) - simplified fixed offset for now or use library if available
    # Since we can't easily install pytz/zoneinfo in restricted env, we add 1 hour (Winter) manually or just label it UTC for now.
    # Better: Use the system time if container timezone is set, otherwise just print formatted string.
    # Let's assume container is UTC. Berlin is UTC+1 (Winter).
    
    # Simple Manual TZ adjustment (approximate, since no pytz)
    # We will just format the string nicely and mention "Session Time"
    
    timestamp_str = now_utc.strftime('%Y-%m-%d %H:%M UTC')
    hours_str = f"{int(hours_invested):02d}:{int((hours_invested*60)%60):02d}"
    
    report_content = (
        f"Investierte Zeit in dieser Session: {hours_str}\n"
        f"Neuer Status: Done\n\n"
        f"Arbeitszusammenfassung:\n{summary}"
    )

    blocks = [
        {
            "object": "block",
            "type": "heading_2",
            "heading_2": {"rich_text": [{"text": {"content": f"🤖 Status-Update ({timestamp_str})"}}] }
        },
        {
            "object": "block",
            "type": "code",
            "code": {
                "rich_text": [{"type": "text", "text": {"content": report_content}}],
                "language": "yaml" # YAML highlighting makes keys look reddish/colored often
            }
        }
    ]
    notion.append_blocks(task_id, blocks)
    
    # 3. Git Commit
    subprocess.run(["git", "add", "."])
    subprocess.run(["git", "commit", "-m", f"[{task_id[:4]}] {summary}"])
    
    # Cleanup
    os.remove(SESSION_FILE)
    print("Session beendet, Notion geupdated, Commited.")

if __name__ == "__main__":
    main()
