#!/usr/bin/env python3
"""
阿里云域名管理工具
功能: 域名列表、详情、续费、转出、过户、信息模板管理
依赖: pip install alibabacloud-domain20180129
"""
import argparse
import json
import sys
import os

def get_client():
    from alibabacloud_domain20180129.client import Client
    from alibabacloud_tea_openapi.models import Config
    ak_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
    ak_secret = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
    if not ak_id or not ak_secret:
        print('ERROR: Set ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET')
        sys.exit(1)
    config = Config(
        access_key_id=ak_id,
        access_key_secret=ak_secret,
        endpoint='domain.aliyuncs.com',
    )
    return Client(config)

# ──────────────── 域名列表 ────────────────

def list_domains(args):
    client = get_client()
    from alibabacloud_domain20180129.models import QueryDomainListRequest
    req = QueryDomainListRequest(
        page_num=args.page,
        page_size=args.size,
    )
    try:
        resp = client.query_domain_list(req)
        body = resp.body
        domains = body.data.domain if body.data and body.data.domain else []
        print(f'\n📋 域名列表 (共 {body.total_item_num} 个)\n')
        print(f'{"域名":<30} {"到期日":<14} {"注册日":<14} {"状态"}')
        print('-' * 75)
        for d in domains:
            exp = d.expiration_date[:10] if d.expiration_date else '-'
            reg = d.registration_date[:10] if d.registration_date else '-'
            # 域名状态
            status = '正常'
            if hasattr(d, 'domain_status') and d.domain_status:
                status = d.domain_status
            print(f'{d.domain_name:<30} {exp:<14} {reg:<14} {status}')
    except Exception as e:
        print(f'ERROR: {e}')

# ──────────────── 域名详情 ────────────────

def domain_info(args):
    client = get_client()
    from alibabacloud_domain20180129.models import QueryDomainByDomainNameRequest
    req = QueryDomainByDomainNameRequest(domain_name=args.domain)
    try:
        resp = client.query_domain_by_domain_name(req)
        body = resp.body
        print(f'\n📋 域名详情: {args.domain}\n')
        print(f'  注册商: {body.registrant_organization or body.registrant_name or "-"}')
        print(f'  注册日: {body.registration_date or "-"}')
        print(f'  到期日: {body.expiration_date or "-"}')
        print(f'  DNS:    {", ".join(body.dns_list.dns) if body.dns_list else "-"}')
        print(f'  状态:   {body.domain_status or "-"}')
        print(f'  实名认证: {"✅ 已认证" if body.zh_registrant_organization else "❌ 未认证"}')
        print(f'  转移锁:  {"🔒 已锁定" if body.transfer_out_status else "🔓 未锁定"}')
        if body.email:
            print(f'  联系邮箱: {body.email}')
    except Exception as e:
        print(f'ERROR: {e}')

# ──────────────── 域名续费 ────────────────

def renew_domain(args):
    client = get_client()
    from alibabacloud_domain20180129.models import SaveSingleTaskForCreatingOrderRenewRequest
    req = SaveSingleTaskForCreatingOrderRenewRequest(
        domain_name=args.domain,
        subscription_duration=args.years,
        current_expiration_date=0,  # will be auto-detected
    )
    try:
        resp = client.save_single_task_for_creating_order_renew(req)
        body = resp.body
        print(f'✅ 续费任务已提交: {args.domain} +{args.years}年')
        print(f'   TaskNo: {body.task_no}')
    except Exception as e:
        print(f'ERROR: {e}')

# ──────────────── 域名转出 ────────────────

def transfer_out(args):
    """获取域名转移密码"""
    client = get_client()
    from alibabacloud_domain20180129.models import TransferOutDomainRequest
    req = TransferOutDomainRequest(domain_name=args.domain)
    try:
        resp = client.transfer_out_domain(req)
        body = resp.body
        print(f'✅ 域名转出已发起: {args.domain}')
        print(f'   转移密码将发送至域名联系人邮箱')
    except Exception as e:
        print(f'ERROR: {e}')

# ──────────────── 信息模板管理 ────────────────

def list_templates(args):
    """查询信息模板"""
    client = get_client()
    from alibabacloud_domain20180129.models import QueryRegistrantProfilesRequest
    req = QueryRegistrantProfilesRequest(
        page_num=args.page,
        page_size=args.size,
    )
    try:
        resp = client.query_registrant_profiles(req)
        body = resp.body
        profiles = body.registrant_profiles.registrant_profile if body.registrant_profiles else []
        print(f'\n📋 信息模板列表 (共 {body.total_item_num} 个)\n')
        print(f'{"模板ID":<12} {"联系人":<20} {"实名认证":<10} {"邮箱":<30} {"类型"}')
        print('-' * 90)
        for p in profiles:
            verified = '✅ 已认证' if p.email_verification_status == 1 else '❌ 未认证'
            rtype = '企业' if p.registrant_type == 'e' else '个人'
            name = p.zh_registrant_organization or p.registrant_name or '-'
            print(f'{p.registrant_profile_id:<12} {name:<20} {verified:<10} {p.email or "-":<30} {rtype}')
    except Exception as e:
        print(f'ERROR: {e}')

# ──────────────── 任务查询 ────────────────

def query_task(args):
    """查询任务详情"""
    client = get_client()
    from alibabacloud_domain20180129.models import QueryTaskDetailListRequest
    req = QueryTaskDetailListRequest(
        task_no=args.task_no,
        page_num=1,
        page_size=20,
    )
    try:
        resp = client.query_task_detail_list(req)
        body = resp.body
        items = body.data.task_detail if body.data else []
        print(f'\n📋 任务详情: {args.task_no}\n')
        for item in items:
            print(f'  域名: {item.domain_name}')
            print(f'  状态: {item.task_status}')
            print(f'  结果: {item.task_result or "-"}')
    except Exception as e:
        print(f'ERROR: {e}')

# ──────────────── CLI ────────────────

def main():
    parser = argparse.ArgumentParser(description='阿里云域名管理工具')
    sub = parser.add_subparsers(dest='command')

    # 域名列表
    p = sub.add_parser('list', help='列出所有域名')
    p.add_argument('--page', type=int, default=1)
    p.add_argument('--size', type=int, default=20)

    # 域名详情
    p = sub.add_parser('info', help='查询域名详情')
    p.add_argument('--domain', required=True, help='域名')

    # 续费
    p = sub.add_parser('renew', help='域名续费')
    p.add_argument('--domain', required=True, help='域名')
    p.add_argument('--years', type=int, default=1, help='续费年数')

    # 转出
    p = sub.add_parser('transfer-out', help='域名转出 (获取转移密码)')
    p.add_argument('--domain', required=True, help='域名')

    # 信息模板
    p = sub.add_parser('list-templates', help='查询信息模板')
    p.add_argument('--page', type=int, default=1)
    p.add_argument('--size', type=int, default=20)

    # 任务查询
    p = sub.add_parser('query-task', help='查询任务状态')
    p.add_argument('--task-no', required=True, help='任务编号')

    args = parser.parse_args()
    if not args.command:
        parser.print_help()
        return

    cmds = {
        'list': list_domains,
        'info': domain_info,
        'renew': renew_domain,
        'transfer-out': transfer_out,
        'list-templates': list_templates,
        'query-task': query_task,
    }
    cmds[args.command](args)

if __name__ == '__main__':
    main()
