import os
import argparse
from pathlib import Path
import json
import sys
import subprocess

BASE_DIR = r"C:\\ContaCam\\Web Camera\\2026"

def latest_file(exts):
    files = []
    for root, _, filenames in os.walk(BASE_DIR):
        for name in filenames:
            if any(name.lower().endswith(ext) for ext in exts):
                full = Path(root) / name
                files.append(full)
    if not files:
        return None
    files.sort(key=lambda p: p.stat().st_mtime, reverse=True)
    return files[0]

def upload(file_path):
    import requests
    with open(os.path.join(os.path.dirname(__file__), "..", "config.json"), "r", encoding="utf-8") as f:
        cfg = json.load(f)
    url = cfg["upload_url"]
    key = cfg["access_key"]
    files = {"file": open(file_path, "rb")}
    data = {"access_key": key}
    resp = requests.post(url, files=files, data=data)
    try:
        j = resp.json()
        if j.get("code") == 200:
            return j["url"]
    except Exception:
        pass
    return None

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--type", choices=["video", "image", "all"], default="all")
    args = parser.parse_args()

    ext_map = {"video": ["mp4"], "image": ["jpg", "gif"], "all": ["mp4", "jpg", "gif"]}
    latest = latest_file(ext_map[args.type])
    if not latest:
        print("No file found")
        sys.exit(1)

    if args.type == "video":
        # 只返回本地路径，调用方可自行决定是否上传
        print(str(latest))
    else:
        url = upload(str(latest))
        if url:
            print(url)
        else:
            print("Upload failed")
            sys.exit(1)

if __name__ == "__main__":
    main()
