#!/usr/bin/env python3
"""Cross-platform entrypoint for meeting minutes flow."""

from __future__ import annotations

import argparse
import json
import subprocess
import sys
from pathlib import Path
from urllib.parse import urlparse

from _resolve_lark_cli import resolve_lark_cli_prefix


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Run meeting-minutes flow from Feishu minutes URL or token."
    )
    parser.add_argument("minutes_url_or_token", help="minutes URL or minute_token")
    parser.add_argument(
        "--output-dir",
        default=str(Path.home() / ".openclaw" / "workspace" / ".meeting-minutes"),
        help="artifact output dir",
    )
    parser.add_argument("--job-id", help="optional custom job id")
    return parser.parse_args()


def extract_token(raw: str) -> str:
    if raw.startswith("http://") or raw.startswith("https://"):
        parsed = urlparse(raw)
        token = parsed.path.rstrip("/").split("/")[-1]
        return token
    return raw.strip()


def main() -> int:
    args = parse_args()
    token = extract_token(args.minutes_url_or_token)
    if not token:
        print(
            json.dumps(
                {"status": "failed", "error_message": "missing minute_token"},
                ensure_ascii=False,
            )
        )
        return 1

    script_dir = Path(__file__).resolve().parent
    base_dir = script_dir.parent
    cli_prefix = resolve_lark_cli_prefix(base_dir)
    runner = script_dir / "openclaw_meeting_minutes.py"
    job_id = args.job_id or f"meeting-minutes-{token}"

    proc = subprocess.run(
        [
            sys.executable,
            str(runner),
            *sum([["--lark-cli-prefix", p] for p in cli_prefix], []),
            "--minute-token",
            token,
            "--job-id",
            job_id,
            "--output-dir",
            args.output_dir,
        ],
        capture_output=True,
        text=True,
    )
    if proc.stdout:
        sys.stdout.write(proc.stdout)
    if proc.stderr:
        sys.stderr.write(proc.stderr)
    return proc.returncode


if __name__ == "__main__":
    raise SystemExit(main())
