"""
Populate missing reporting_tag values on accounting codes using the same
heuristics as the cash flow statement. Run once to ensure accounts are
classified for Operating, Investing, or Financing cash flows.
"""
from __future__ import annotations

import argparse
from typing import Dict

from app.core.database import SessionLocal
from app.models.accounting import AccountingCode
from app.services.financial_statements_service import FinancialStatementsService


def infer_and_apply_tags(dry_run: bool = False, force: bool = False) -> Dict[str, int]:
    session = SessionLocal()
    service = FinancialStatementsService(session)

    tag_counts: Dict[str, int] = {}
    updated = 0

    try:
        accounts = session.query(AccountingCode).all()
        for account in accounts:
            existing = (account.reporting_tag or "").strip()

            if existing and not force:
                continue

            inferred = service._derive_reporting_tag(account)

            if existing == inferred:
                continue

            account.reporting_tag = inferred
            updated += 1
            tag_counts[inferred] = tag_counts.get(inferred, 0) + 1

        if dry_run:
            session.rollback()
        else:
            session.commit()

        return {
            "processed": len(accounts),
            "updated": updated,
            **{f"tag_{k}": v for k, v in tag_counts.items()},
        }
    finally:
        session.close()


def main() -> None:
    parser = argparse.ArgumentParser(description="Apply reporting tags to accounting codes")
    parser.add_argument("--dry-run", action="store_true", help="Show what would change without committing")
    parser.add_argument("--force", action="store_true", help="Override existing reporting_tag values with inferred cash flow tags")
    args = parser.parse_args()

    stats = infer_and_apply_tags(dry_run=args.dry_run, force=args.force)

    print(f"Processed: {stats.get('processed', 0)} accounts")
    print(f"Updated: {stats.get('updated', 0)} accounts")
    for key, value in stats.items():
        if key.startswith("tag_"):
            print(f"  {key.replace('tag_', '')}: {value}")

    if args.dry_run:
        print("Dry run complete; no database changes were committed.")
    if args.force:
        print("Force mode: existing reporting_tag values were overwritten with inferred cash flow tags where they differed.")


if __name__ == "__main__":
    main()
