#!/usr/bin/env python3
"""squashr-tags-export — Export MedMan tags for squashr container inclusion."""
import argparse, json, os, sys, sqlite3
from datetime import datetime, timezone

def main():
    p = argparse.ArgumentParser(description="Export MedMan tags for squashr")
    p.add_argument("--db", required=True, help="Path to medman.db")
    p.add_argument("--dat", required=True, help="Comma-separated data dirs")
    p.add_argument("--manifest", help="Path to squashr manifest file")
    p.add_argument("--output", required=True, help="Output JSON path")
    p.add_argument("--pretty", action="store_true")
    a = p.parse_args()

    if not os.path.isfile(a.db): print(f"Error: {a.db} not found", file=sys.stderr); sys.exit(1)

    mf: set|None = None
    if a.manifest:
        with open(a.manifest) as f: mf = {l.strip() for l in f if l.strip()}

    db = sqlite3.connect(a.db); db.row_factory = sqlite3.Row
    rows = db.execute("""SELECT ft.hash,f.didx,f.rel,t.name AS tn FROM ftags ft JOIN tags t ON t.id=ft.tid JOIN files f ON f.hash=ft.hash ORDER BY ft.hash,t.name""").fetchall()
    atags = db.execute("SELECT id,name FROM tags ORDER BY name").fetchall()
    db.close()

    ft = {}
    for r in rows:
        h = r["hash"]
        if mf is not None and h not in mf: continue
        ft.setdefault(h, {"didx":r["didx"],"tags":[]})["tags"].append(r["tn"])

    exp = {"ts":datetime.now(timezone.utc).isoformat(),"tags":[dict(t) for t in atags],"files":ft}
    with open(a.output,"w") as f: json.dump(exp, f, indent=2 if a.pretty else None)
    print(f"Exported {len(ft)} files to {a.output}")

if __name__ == "__main__": main()
