#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os, sys, io, sqlite3, cgitb, html

cgitb.enable()
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
print('Content-Type: text/html; charset=utf-8\n')

TEMPLATE_HEADER = 'temp/header.txt'
TEMPLATE_FOOTER = 'temp/footer.txt'
DB_PATH = os.path.join('data', 'year_archive.db')

def read_template(path):
    try:
        with open(path, encoding='utf-8') as f:
            return f.read()
    except:
        return f'<!-- {path} が読み込めませんでした -->'

def h(s):
    return html.escape(str(s) if s is not None else '')

header = read_template(TEMPLATE_HEADER)
footer = read_template(TEMPLATE_FOOTER)
rows = []
if os.path.exists(DB_PATH):
    conn = sqlite3.connect(DB_PATH)
    try:
        cur = conn.cursor()
        cur.execute('''
            SELECT id, archive_label, source_kind, source_db, source_table, source_nendo, created_at, note
            FROM fiscal_archive
            ORDER BY id DESC
            LIMIT 200
        ''')
        rows = cur.fetchall()
    except:
        rows = []
    finally:
        conn.close()

print(header)
print('''<div class="container py-4">
<h2 class="mb-3">年度バックアップ一覧</h2>
<p class="text-muted">年度切替前に保存したスナップショットの一覧です。</p>
<div class="mb-3 d-flex gap-2 flex-wrap">
<a href="year_rollover.py" class="btn btn-primary">年度切替画面へ</a>
<a href="index.html" class="btn btn-secondary">ホームへ</a>
</div>
<div class="table-responsive"><table class="table table-bordered table-striped align-middle">
<thead class="table-dark"><tr><th>ID</th><th>バックアップ名</th><th>種類</th><th>DB</th><th>テーブル</th><th>年度</th><th>日時</th><th>メモ</th></tr></thead><tbody>''')
if rows:
    for r in rows:
        print(f'<tr><td>{h(r[0])}</td><td>{h(r[1])}</td><td>{h(r[2])}</td><td>{h(r[3])}</td><td>{h(r[4])}</td><td>{h(r[5])}</td><td>{h(r[6])}</td><td>{h(r[7])}</td></tr>')
else:
    print('<tr><td colspan="8" class="text-center text-muted">まだバックアップはありません。</td></tr>')
print('</tbody></table></div></div>')
print(footer)
