#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Market intelligence seed writer CLI.

By default this script prints a JSON execution plan. Real writes require
--execute, --apply-real-write, and a confirmation token.
"""

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


REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))

with contextlib.redirect_stdout(sys.stderr):
    from services.market_intel import MarketIntelService  # noqa: E402
    from services.market_intel.seed_writer_cli import APPROVAL_ENV_VAR  # noqa: E402


def parse_args(argv=None):
    parser = argparse.ArgumentParser(
        description="Preview market_intel platform seed writer execution."
    )
    parser.add_argument(
        "--platform",
        default="all",
        help="Platform code to preview, or all. Default: all.",
    )
    parser.add_argument(
        "--execute",
        action="store_true",
        help="Request real execution.",
    )
    parser.add_argument(
        "--apply-real-write",
        action="store_true",
        help="Allow the guarded market_platforms seed upsert transaction.",
    )
    parser.add_argument(
        "--approval-token",
        default=None,
        help=f"One-time approval token. Defaults to {APPROVAL_ENV_VAR} when omitted.",
    )
    return parser.parse_args(argv)


def main(argv=None):
    args = parse_args(argv)
    approval_token_secret = os.getenv(APPROVAL_ENV_VAR)
    approval_token = args.approval_token or approval_token_secret
    service = MarketIntelService()
    plan = service.build_seed_writer_cli_status(
        platform_code=args.platform,
        execute_requested=args.execute,
        apply_real_write=args.apply_real_write,
        approval_token=approval_token,
        approval_token_secret=approval_token_secret,
    )
    print(json.dumps(plan, ensure_ascii=False, indent=2, sort_keys=True))
    return int(plan.get("exit_code", 2))


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